/**
 * Content Auditor — batched scan with progress, plus clear.
 * Hardened against non-JSON responses like the rest of the plugin.
 */
(function () {
	'use strict';
	var CFG = window.PlatformHelmAudit || {};

	function ajax(action, data) {
		var body = new FormData();
		body.append('action', action);
		body.append('nonce', CFG.nonce);
		Object.keys(data || {}).forEach(function (k) { body.append(k, data[k]); });
		return fetch(CFG.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: body })
			.then(function (r) { return r.text(); })
			.then(function (t) {
				var j;
				try { j = JSON.parse(t); }
				catch (e) { throw new Error('Unexpected server response (possible timeout). Try again.'); }
				if (!j || j.success !== true) { throw new Error((j && j.data && j.data.message) || 'Request failed.'); }
				return j.data;
			});
	}

	function briefRowFor(btn) {
		var tr = btn.closest ? btn.closest('tr') : null;
		if (!tr || !tr.parentNode) { return null; }
		var next = tr.nextElementSibling;
		if (next && next.classList.contains('ph-ca-brief-row')) { return next; }
		var row = document.createElement('tr');
		row.className = 'ph-ca-brief-row';
		var td = document.createElement('td');
		td.colSpan = 11;
		td.style.background = '#f6f8fb';
		row.appendChild(td);
		tr.parentNode.insertBefore(row, tr.nextSibling);
		return row;
	}

	document.addEventListener('click', function (e) {
		var btn = (e.target && e.target.closest) ? e.target.closest('.ph-ca-brief') : null;
		if (!btn) { return; }
		e.preventDefault();
		var id = btn.getAttribute('data-id');
		if (!id) { return; }
		var row = briefRowFor(btn);
		var cell = row ? row.firstChild : null;
		if (cell) { cell.innerHTML = '<em>Generating refresh brief… (a few seconds)</em>'; }
		btn.disabled = true;
		ajax(CFG.briefAction, { post_id: id })
			.then(function (d) {
				if (cell) {
					cell.innerHTML = '';
					var box = document.createElement('div');
					box.className = 'ph-ca-brief-text';
					box.textContent = d.brief || 'No brief returned.';
					box.style.whiteSpace = 'pre-wrap';
					box.style.lineHeight = '1.55';
					box.style.padding = '12px';
					box.style.background = '#fff';
					box.style.border = '1px solid #e0e6ee';
					box.style.borderRadius = '6px';
					cell.appendChild(box);
				}
				btn.disabled = false;
			})
			.catch(function (err) {
				if (cell) { cell.innerHTML = '<span class="is-error">⚠ ' + err.message + '</span>'; }
				btn.disabled = false;
			});
	});

	function msg(text, isErr) {
		var el = document.getElementById('ph-ca-msg');
		if (el) { el.textContent = (isErr ? '⚠ ' : '') + text; el.className = 'ph-ca-msg' + (isErr ? ' is-error' : ' is-ok'); }
	}

	function bulkMsg(text, isErr) {
		var el = document.getElementById('ph-ca-bulkmsg');
		if (el) { el.textContent = (isErr ? '⚠ ' : '') + text; el.className = 'ph-ca-msg' + (isErr ? ' is-error' : ' is-ok'); }
	}

	function selectedIds() {
		return Array.prototype.slice.call(document.querySelectorAll('.ph-ca-cb:checked')).map(function (c) { return c.value; });
	}

	function updateCount() {
		var el = document.getElementById('ph-ca-selcount');
		var n = selectedIds().length;
		if (el) el.textContent = n ? (n + ' selected') : '';
	}

	function runBulk(action, extra, ids, done) {
		// Send in chunks of 25 (server caps at 50/req) to protect WP Engine.
		var chunks = [];
		for (var i = 0; i < ids.length; i += 25) chunks.push(ids.slice(i, i + 25));
		var affected = 0, idx = 0;
		function next() {
			if (idx >= chunks.length) { done(affected); return; }
			var body = { };
			Object.keys(extra || {}).forEach(function (k) { body[k] = extra[k]; });
			var fd = new FormData();
			fd.append('action', action);
			fd.append('nonce', CFG.nonce);
			Object.keys(body).forEach(function (k) { fd.append(k, body[k]); });
			chunks[idx].forEach(function (id) { fd.append('ids[]', id); });
			fetch(CFG.ajaxUrl, { method: 'POST', credentials: 'same-origin', body: fd })
				.then(function (r) { return r.text(); })
				.then(function (t) {
					var j; try { j = JSON.parse(t); } catch (e) { throw new Error('Unexpected server response (possible timeout).'); }
					if (!j || j.success !== true) { throw new Error((j && j.data && j.data.message) || 'Request failed.'); }
					affected += (j.data && j.data.affected) || 0;
					idx++;
					bulkMsg('Working… ' + affected + ' done', false);
					next();
				})
				.catch(function (err) { bulkMsg(err.message, true); });
		}
		next();
	}

	document.addEventListener('DOMContentLoaded', function () {
		// --- selection + bulk actions ---
		var selectAll = document.getElementById('ph-ca-selectall');
		if (selectAll) {
			selectAll.addEventListener('change', function () {
				Array.prototype.slice.call(document.querySelectorAll('.ph-ca-cb')).forEach(function (c) { c.checked = selectAll.checked; });
				updateCount();
			});
		}
		document.addEventListener('change', function (e) {
			if (e.target && e.target.classList && e.target.classList.contains('ph-ca-cb')) updateCount();
		});

		var applyBtn = document.getElementById('ph-ca-apply');
		if (applyBtn) {
			applyBtn.addEventListener('click', function () {
				var sel = document.getElementById('ph-ca-bulk');
				var act = sel ? sel.value : '';
				var ids = selectedIds();
				if (!act) { bulkMsg('Pick an action first.', true); return; }
				if (!ids.length) { bulkMsg('Select at least one post.', true); return; }

				var map = {
					mark_done: { action: 'platform_helm_audit_mark', extra: { handled: 1 }, confirm: '' },
					mark_open: { action: 'platform_helm_audit_mark', extra: { handled: 0 }, confirm: '' },
					noindex:   { action: 'platform_helm_audit_noindex', extra: {}, confirm: 'Set ' + ids.length + ' post(s) to noindex? This is reversible.' },
					trash:     { action: 'platform_helm_audit_trash', extra: {}, confirm: 'Move ' + ids.length + ' post(s) to Trash?\n\nThis is REVERSIBLE for 30 days. Best practice: set a 301 redirect in Yoast first so you don\'t create 404s. Continue?' }
				};
				var cfg = map[act];
				if (!cfg) { bulkMsg('Unknown action.', true); return; }

				if (act === 'trash') {
					var rt = ((document.getElementById('ph-ca-redirect') || {}).value || '').trim();
					if (rt) {
						cfg.extra = { redirect_target: rt };
						cfg.confirm = 'Move ' + ids.length + ' post(s) to Trash AND create a 301 redirect to "' + rt + '" for each?\n\nTrash is reversible for 30 days. Continue?';
					}
				}

				if (cfg.confirm && !confirm(cfg.confirm)) return;

				applyBtn.disabled = true;
				bulkMsg('Working…', false);
				runBulk(cfg.action, cfg.extra, ids, function (affected) {
					bulkMsg('Done — ' + affected + ' updated. Reloading…', false);
					setTimeout(function () { window.location.reload(); }, 1100);
				});
			});
		}

		// --- audit scan ---
		var runBtn = document.getElementById('ph-ca-run');
		if (!runBtn) return;

		runBtn.addEventListener('click', function () {
			if (!confirm('Run the audit now? On a large site this scans all posts in batches and can take a few minutes. Keep this tab open.')) return;
			runBtn.disabled = true;
			var prog = document.getElementById('ph-ca-progress');
			var bar = document.getElementById('ph-ca-bar');
			if (prog) prog.hidden = false;

			function step(offset, reset) {
				return ajax('platform_helm_audit_scan', { offset: offset, reset: reset ? 1 : 0 })
					.then(function (d) {
						var total = d.total || 0;
						var done = d.offset || 0;
						if (bar && total) bar.style.width = Math.min(100, Math.round((done / total) * 100)) + '%';
						msg('Scanned ' + done + ' of ' + total + ' posts…', false);
						if (d.processed > 0 && done < total) {
							return step(done, false);
						}
						msg('Audit complete — ' + done + ' posts scored. Reloading…', false);
						setTimeout(function () { window.location.href = window.location.pathname + '?page=' + (new URLSearchParams(window.location.search).get('page') || 'platform-helm-content-auditor'); }, 1000);
					});
			}

			step(0, true).catch(function (err) {
				msg(err.message, true);
				runBtn.disabled = false;
			});
		});
	});
})();
