/**
 * Answyr Desk — draft-and-vet flow.
 * Suggest (AI draft) → edit → Send. The AI never sends; the agent clicks Send.
 */
(() => {
	var cfg = window.AnswyrDesk || { restBase: '', nonce: '' };
	var wrap = document.querySelector('.answyr-desk');
	if (!wrap) {
		return;
	}

	var ticketId = wrap.getAttribute('data-ticket');
	var suggestBtn = document.getElementById('answyr-suggest');
	var polishBtn = document.getElementById('answyr-polish');
	var sendBtn = document.getElementById('answyr-send');
	var body = document.getElementById('answyr-reply-body');
	var suggestStatus = document.getElementById('answyr-suggest-status');
	var sendStatus = document.getElementById('answyr-send-status');
	var sourcesBox = document.getElementById('answyr-sources');
	var statusSelect = document.getElementById('answyr-status-select');
	var statusPill = document.getElementById('answyr-status-pill');
	var statusResult = document.getElementById('answyr-status-result');
	var prioritySelect = document.getElementById('answyr-priority-select');
	var priorityPill = document.getElementById('answyr-priority-pill');
	var tagsInput = document.getElementById('answyr-tags-input');
	var tagsSave = document.getElementById('answyr-tags-save');
	var tagsResult = document.getElementById('answyr-tags-result');
	var cannedSelect = document.getElementById('answyr-canned');
	var noteBody = document.getElementById('answyr-note-body');
	var noteAdd = document.getElementById('answyr-note-add');
	var noteStatus = document.getElementById('answyr-note-status');
	var cannedEl = document.getElementById('answyr-canned-data');
	var canned = cannedEl ? JSON.parse(cannedEl.textContent || '[]') : [];

	// Compose helpers — the reply box is the WordPress editor, so read/write goes
	// through TinyMCE when its Visual mode is active and falls back to the raw
	// textarea in Text mode. Exposed on window so the Pro macros script can reuse it.
	var EDITOR_ID = 'answyr-reply-body';
	function activeEditor() {
		var ed = window.tinymce ? window.tinymce.get(EDITOR_ID) : null;
		return ed && !ed.isHidden() ? ed : null;
	}
	function escHtml(s) {
		return String(s).replace(/[&<>]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;' })[c]);
	}
	function textToHtml(text) {
		return String(text)
			.split(/\n{2,}/)
			.map((p) => `<p>${escHtml(p).replace(/\n/g, '<br>')}</p>`)
			.join('');
	}
	function getBody() {
		var ed = activeEditor();
		return ed ? ed.getContent() : body ? body.value : '';
	}
	function isEmpty() {
		return !getBody()
			.replace(/<[^>]*>/g, '')
			.trim();
	}
	function setBodyPlain(text) {
		var ed = activeEditor();
		if (ed) {
			ed.setContent(textToHtml(text));
		} else if (body) {
			body.value = text;
		}
	}
	function appendPlain(text) {
		var ed = activeEditor();
		var cur;
		if (ed) {
			cur = ed.getContent();
			ed.setContent(cur ? cur + textToHtml(text) : textToHtml(text));
		} else if (body) {
			body.value = body.value ? `${body.value}\n\n${text}` : text;
		}
	}
	function focusBody() {
		var ed = activeEditor();
		if (ed) {
			ed.focus();
		} else if (body) {
			body.focus();
		}
	}
	window.AnswyrCompose = {
		get: getBody,
		isEmpty: isEmpty,
		setPlain: setBodyPlain,
		appendPlain: appendPlain,
		focus: focusBody,
	};

	function api(path, payload) {
		return fetch(cfg.restBase + path, {
			method: 'POST',
			headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': cfg.nonce },
			body: JSON.stringify(payload || {}),
		}).then((r) => r.json().then((data) => ({ ok: r.ok, data: data })));
	}

	function renderSources(sources) {
		if (!sourcesBox) {
			return;
		}
		var ul = sourcesBox.querySelector('ul');
		ul.innerHTML = '';
		if (!sources || !sources.length) {
			sourcesBox.hidden = true;
			return;
		}
		sources.forEach((s) => {
			var li = document.createElement('li');
			var a = document.createElement('a');
			a.href = s.url;
			a.target = '_blank';
			a.rel = 'noopener';
			a.textContent = s.title || s.url;
			li.appendChild(a);
			ul.appendChild(li);
		});
		sourcesBox.hidden = false;
	}

	if (suggestBtn) {
		suggestBtn.addEventListener('click', () => {
			suggestBtn.disabled = true;
			suggestStatus.textContent = 'Drafting…';
			api(`/desk/tickets/${ticketId}/suggest`, {})
				.then((res) => {
					if (!res.ok || res.data.error) {
						suggestStatus.textContent = `✗ ${res.data.error || 'Failed'}`;
						return;
					}
					setBodyPlain(res.data.draft || '');
					renderSources(res.data.sources);
					suggestStatus.textContent = 'Draft ready';
				})
				.catch((e) => {
					suggestStatus.textContent = `✗ ${e.message}`;
				})
				.finally(() => {
					suggestBtn.disabled = false;
				});
		});
	}

	// Polish (Pro): rewrite the current rough draft, keeping its meaning.
	if (polishBtn) {
		polishBtn.addEventListener('click', () => {
			if (isEmpty()) {
				suggestStatus.textContent = 'Write a draft to polish first.';
				return;
			}
			polishBtn.disabled = true;
			suggestStatus.textContent = 'Polishing…';
			api(`/desk/tickets/${ticketId}/polish`, { body: getBody() })
				.then((res) => {
					if (!res.ok || res.data.error) {
						suggestStatus.textContent = `✗ ${res.data.error || 'Failed'}`;
						return;
					}
					setBodyPlain(res.data.polished || '');
					suggestStatus.textContent = 'Polished ✓';
				})
				.catch((e) => {
					suggestStatus.textContent = `✗ ${e.message}`;
				})
				.finally(() => {
					polishBtn.disabled = false;
				});
		});
	}

	if (sendBtn) {
		sendBtn.addEventListener('click', () => {
			if (isEmpty()) {
				sendStatus.textContent = 'Nothing to send.';
				return;
			}
			sendBtn.disabled = true;
			sendStatus.textContent = 'Sending…';
			api(`/desk/tickets/${ticketId}/reply`, { body: getBody() })
				.then((res) => {
					if (!res.ok || res.data.error) {
						sendStatus.textContent = `✗ ${res.data.error || 'Failed'}`;
						sendBtn.disabled = false;
						return;
					}
					sendStatus.textContent = res.data.delivered ? 'Sent ✓' : 'Saved (email not delivered)';
					setTimeout(() => {
						window.location.reload();
					}, 800);
				})
				.catch((e) => {
					sendStatus.textContent = `✗ ${e.message}`;
					sendBtn.disabled = false;
				});
		});
	}

	if (statusSelect) {
		statusSelect.addEventListener('change', () => {
			var status = statusSelect.value;
			var label = statusSelect.options[statusSelect.selectedIndex].text;
			statusSelect.disabled = true;
			if (statusResult) {
				statusResult.textContent = 'Saving…';
			}
			api(`/desk/tickets/${ticketId}/status`, { status: status })
				.then((res) => {
					if (!res.ok || res.data.error) {
						if (statusResult) {
							statusResult.textContent = `✗ ${res.data.error || 'Failed'}`;
						}
						return;
					}
					if (statusPill) {
						statusPill.className = `answyr-pill answyr-pill-${status}`;
						statusPill.textContent = label;
					}
					if (statusResult) {
						statusResult.textContent = 'Saved ✓';
					}
				})
				.catch((e) => {
					if (statusResult) {
						statusResult.textContent = `✗ ${e.message}`;
					}
				})
				.finally(() => {
					statusSelect.disabled = false;
				});
		});
	}

	if (prioritySelect) {
		prioritySelect.addEventListener('change', () => {
			var priority = prioritySelect.value;
			var label = prioritySelect.options[prioritySelect.selectedIndex].text;
			prioritySelect.disabled = true;
			api(`/desk/tickets/${ticketId}/priority`, { priority: priority })
				.then((res) => {
					if (res.ok && !res.data.error && priorityPill) {
						priorityPill.className = `answyr-pri answyr-pri-${priority}`;
						priorityPill.textContent = label;
					}
				})
				.finally(() => {
					prioritySelect.disabled = false;
				});
		});
	}

	if (tagsSave && tagsInput) {
		tagsSave.addEventListener('click', () => {
			tagsSave.disabled = true;
			if (tagsResult) {
				tagsResult.textContent = 'Saving…';
			}
			api(`/desk/tickets/${ticketId}/tags`, { tags: tagsInput.value })
				.then((res) => {
					if (tagsResult) {
						tagsResult.textContent =
							res.ok && !res.data.error ? 'Saved ✓' : `✗ ${res.data.error || 'Failed'}`;
					}
				})
				.finally(() => {
					tagsSave.disabled = false;
				});
		});
	}

	// Insert a saved reply into the compose box.
	if (cannedSelect && body) {
		cannedSelect.addEventListener('change', () => {
			var idx = cannedSelect.value;
			if (idx === '' || !canned[idx]) {
				return;
			}
			appendPlain(canned[idx]);
			cannedSelect.selectedIndex = 0;
			focusBody();
		});
	}

	if (noteAdd && noteBody) {
		noteAdd.addEventListener('click', () => {
			if (!noteBody.value.trim()) {
				noteStatus.textContent = 'Write a note first.';
				return;
			}
			noteAdd.disabled = true;
			noteStatus.textContent = 'Saving…';
			api(`/desk/tickets/${ticketId}/note`, { body: noteBody.value })
				.then((res) => {
					if (!res.ok || res.data.error) {
						noteStatus.textContent = `✗ ${res.data.error || 'Failed'}`;
						noteAdd.disabled = false;
						return;
					}
					noteStatus.textContent = 'Added ✓';
					setTimeout(() => window.location.reload(), 600);
				})
				.catch((e) => {
					noteStatus.textContent = `✗ ${e.message}`;
					noteAdd.disabled = false;
				});
		});
	}

	// Keyboard: ⌘/Ctrl+Enter sends the reply — bound to both the raw textarea
	// (Text mode) and the TinyMCE instance (Visual mode).
	function sendOnCmdEnter(e) {
		if ((e.metaKey || e.ctrlKey) && e.key === 'Enter') {
			e.preventDefault();
			sendBtn.click();
		}
	}
	if (body && sendBtn) {
		body.addEventListener('keydown', sendOnCmdEnter);
	}
	if (sendBtn && window.tinymce) {
		window.tinymce.on('AddEditor', (e) => {
			if (e.editor.id === EDITOR_ID) {
				e.editor.on('keydown', sendOnCmdEnter);
			}
		});
	}
})();
