/**
 * Content brief from Trend Radar (dashboard desk workflow).
 */
(function ($) {
	'use strict';

	var __ = (typeof wp !== 'undefined' && wp.i18n && typeof wp.i18n.__ === 'function')
		? function (text) { return wp.i18n.__(text, 'newsroom-ai-assistant'); }
		: function (text) { return text; };

	function escapeHtml(s) {
		return String(s == null ? '' : s)
			.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;').replace(/'/g, '&#39;');
	}

	function resolveGeo() {
		var $geo = $('#newsai-trends-geo');
		if ($geo.length) {
			return String($geo.val() || '');
		}
		return (typeof newsai_vars !== 'undefined' && newsai_vars.geo) ? String(newsai_vars.geo) : '';
	}

	function flashField($el) {
		$el.css('box-shadow', '0 0 0 3px rgba(34, 113, 177, 0.4)');
		setTimeout(function () { $el.css('box-shadow', ''); }, 1200);
	}

	function scrollToBriefBar() {
		var bar = document.getElementById('newsai-brief-bar');
		if (bar) {
			bar.scrollIntoView({ behavior: 'smooth', block: 'nearest' });
		}
	}

	$(document).on('click', '.nros-copy-task-btn', function (e) {
		e.preventDefault();
		var btn = $(this);
		var text = $.trim(String(btn.data('title') || btn.attr('data-title') || ''));
		var originalText = btn.html();

		function flashBtn(ok) {
			btn.html(ok ? '✅' : '❌');
			setTimeout(function () { btn.html(originalText); }, 2000);
		}

		var $brief = $('#newsai-brief-topic');
		if ($brief.length && text) {
			$brief.val(text).trigger('input').focus();
			flashField($brief);
			scrollToBriefBar();
			flashBtn(true);
			return;
		}

		var taskInput = document.getElementById('nros-task-input');
		if (taskInput && text) {
			taskInput.value = text;
			var taskFormCard = document.getElementById('nros-task-form-card');
			if (taskFormCard) {
				taskFormCard.open = true;
				taskFormCard.scrollIntoView({ behavior: 'smooth', block: 'center' });
			}
			taskInput.focus();
			flashField($(taskInput));
			flashBtn(true);
			return;
		}

		if (!text) {
			flashBtn(false);
		}
	});

	(function initContentBrief() {
		var $topic = $('#newsai-brief-topic');
		var $btn = $('#newsai-brief-generate');
		var $out = $('#newsai-brief-output');
		var $taskTools = $('#newsai-brief-task-tools');
		var $taskBtn = $('#newsai-brief-create-task');
		var $taskStatus = $('#newsai-brief-task-status');
		var lastBrief = null;

		if (!$topic.length || !$btn.length || typeof newsai_vars === 'undefined') {
			return;
		}

		$(document).on('click', '#newsai-trends-list a[data-trend-term], #newsai-news-list a[data-trend-term]', function (e) {
			if (e.metaKey || e.ctrlKey || e.shiftKey) {
				return;
			}
			var term = $(this).attr('data-trend-term') || $(this).text();
			$topic.val($.trim(term)).trigger('input').focus();
			$btn.trigger('click');
			e.preventDefault();
		});

		function renderBrief(data) {
			if (!data || !data.angle) {
				$out.html('<em class="nros-brief-error">' + escapeHtml(__('Could not build brief.')) + '</em>');
				return;
			}
			var html = '<h4>' + escapeHtml(data.angle) + '</h4>';
			if (data.target_keywords && data.target_keywords.length) {
				html += '<div><strong>' + escapeHtml(__('Keywords')) + ':</strong> ' + escapeHtml(data.target_keywords.join(', ')) + '</div>';
			}
			if (data.outline && data.outline.length) {
				html += '<div><strong>' + escapeHtml(__('Outline')) + ':</strong><ul>';
				data.outline.forEach(function (line) {
					html += '<li>' + escapeHtml(line) + '</li>';
				});
				html += '</ul></div>';
			}
			if (data.competing_urls && data.competing_urls.length) {
				html += '<div><strong>' + escapeHtml(__('Competing coverage')) + ':</strong><ul>';
				data.competing_urls.forEach(function (row) {
					html += '<li><a href="' + escapeHtml(row.url) + '" target="_blank" rel="noopener noreferrer">' + escapeHtml(row.title) + '</a>';
					if (row.why) {
						html += ' — <span class="nros-brief-muted">' + escapeHtml(row.why) + '</span>';
					}
					html += '</li>';
				});
				html += '</ul></div>';
			}
			$out.html(html);
			if ($taskTools.length) {
				$taskTools.show();
				$taskStatus.empty();
			}
		}

		$btn.on('click', function () {
			var topic = $.trim($topic.val() || '');
			if (!topic) {
				$out.html('<em class="nros-brief-error">' + escapeHtml(__('Enter a topic first.')) + '</em>');
				return;
			}
			var orig = $btn.html();
			$btn.prop('disabled', true).text(__('⏳ Generating…'));
			$out.html('<em class="nros-brief-muted">' + escapeHtml(__('Building brief from live trends & news…')) + '</em>');
			lastBrief = null;
			if ($taskTools.length) {
				$taskTools.hide();
				$taskStatus.empty();
			}
			$.post(newsai_vars.ajax_url, {
				action: 'newsai_ai_content_brief',
				nonce: newsai_vars.nonce,
				topic: topic,
				geo: resolveGeo()
			})
				.done(function (resp) {
					if (!resp || !resp.success) {
						var msg = (resp && resp.data && resp.data.message) || __('AI error.');
						$out.html('<em class="nros-brief-error">' + escapeHtml(String(msg)) + '</em>');
						return;
					}
					renderBrief((resp.data && resp.data.data) || {});
					lastBrief = (resp.data && resp.data.data) ? resp.data.data : null;
					if (resp.data && resp.data.cached) {
						$out.append('<div class="nros-brief-cache-note">' + escapeHtml(__('From cache')) + '</div>');
					}
				})
				.fail(function (xhr) {
					var msg = (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) || __('Network error.');
					$out.html('<em class="nros-brief-error">' + escapeHtml(String(msg)) + '</em>');
				})
				.always(function () {
					$btn.prop('disabled', false).html(orig);
				});
		});

		if ($taskBtn.length) {
			$taskBtn.on('click', function () {
				if (!lastBrief || !lastBrief.angle) {
					$taskStatus.html('<em class="nros-brief-error">' + escapeHtml(__('Generate a brief first.')) + '</em>');
					return;
				}
				var authorId = 0;
				var $assignee = $('#newsai-brief-assignee');
				if ($assignee.length) {
					authorId = parseInt($assignee.val(), 10) || 0;
				}
				var dueDate = String($('#newsai-brief-due-date').val() || '');
				var origTask = $taskBtn.html();
				$taskBtn.prop('disabled', true).text(__('⏳ Creating…'));
				$taskStatus.html('<em class="nros-brief-muted">' + escapeHtml(__('Creating editorial task…')) + '</em>');
				$.post(newsai_vars.ajax_url, {
					action: 'newsai_ai_create_task_from_brief',
					nonce: newsai_vars.nonce,
					brief: JSON.stringify(lastBrief),
					author_id: authorId,
					due_date: dueDate
				})
					.done(function (resp) {
						if (!resp || !resp.success) {
							var err = (resp && resp.data && resp.data.message) || __('Could not create task.');
							$taskStatus.html('<em class="nros-brief-error">' + escapeHtml(String(err)) + '</em>');
							return;
						}
						var ok = (resp.data && resp.data.message) || __('Editorial task created.');
						var link = (resp.data && resp.data.settings_url) || '';
						var html = '<span class="nros-brief-success">✓ ' + escapeHtml(String(ok)) + '</span>';
						if (link) {
							html += ' <a href="' + escapeHtml(link) + '">' + escapeHtml(__('View tasks')) + '</a>';
						}
						$taskStatus.html(html);
					})
					.fail(function (xhr) {
						var err = (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) || __('Network error.');
						$taskStatus.html('<em class="nros-brief-error">' + escapeHtml(String(err)) + '</em>');
					})
					.always(function () {
						$taskBtn.prop('disabled', false).html(origTask);
					});
			});
		}
	}());
}(jQuery));
