/**
 * Email Logs admin: settings modal, view modal, HTML preview.
 */
(function () {
	'use strict';

	var cfg = window.wppsEmailLogs || {};
	var ajaxUrl = cfg.ajaxUrl || window.ajaxurl;
	var nonce = cfg.nonce || '';
	var i18n = cfg.i18n || {};

	function qs(sel, root) {
		return (root || document).querySelector(sel);
	}

	function qsa(sel, root) {
		return Array.prototype.slice.call((root || document).querySelectorAll(sel));
	}

	function openModal(el) {
		if (!el) return;
		el.classList.add('is-open');
		el.setAttribute('aria-hidden', 'false');
		document.body.classList.add('wpps-el-modal-open');
	}

	function closeModal(el) {
		if (!el) return;
		el.classList.remove('is-open');
		el.setAttribute('aria-hidden', 'true');
		if (!qs('.wpps-el-modal.is-open')) {
			document.body.classList.remove('wpps-el-modal-open');
		}
	}

	function closeAllModals() {
		qsa('.wpps-el-modal.is-open').forEach(closeModal);
	}

	function badge(text, cls) {
		return '<span class="wpps-el-badge ' + cls + '">' + escapeHtml(text) + '</span>';
	}

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

	var PREVIEW_BLANK =
		'<!DOCTYPE html><html><head><meta charset="utf-8"></head><body></body></html>';
	var previewObjectUrl = '';

	function revokePreviewUrl() {
		if (previewObjectUrl) {
			URL.revokeObjectURL(previewObjectUrl);
			previewObjectUrl = '';
		}
	}

	/**
	 * Sandboxed preview never allows scripts; strip them so Chrome does not warn on about:blank.
	 */
	function sanitizePreviewHtml(html) {
		var raw = html == null ? '' : String(html);
		if (!raw) {
			return PREVIEW_BLANK;
		}
		try {
			var doc = new DOMParser().parseFromString(raw, 'text/html');
			if (!doc || !doc.documentElement) {
				return raw;
			}
			doc.querySelectorAll('script, iframe, object, embed, link[rel="import"]').forEach(function (node) {
				node.remove();
			});
			doc.querySelectorAll('*').forEach(function (el) {
				Array.prototype.slice.call(el.attributes || []).forEach(function (attr) {
					if (/^on/i.test(attr.name) || /^javascript:/i.test(attr.value || '')) {
						el.removeAttribute(attr.name);
					}
				});
			});
			if (doc.head && !doc.querySelector('meta[name="viewport"]')) {
				var meta = doc.createElement('meta');
				meta.setAttribute('name', 'viewport');
				meta.setAttribute('content', 'width=device-width, initial-scale=1');
				doc.head.insertBefore(meta, doc.head.firstChild);
			}
			return '<!DOCTYPE html>' + doc.documentElement.outerHTML;
		} catch (e) {
			return raw
				.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi, '')
				.replace(/\son\w+\s*=\s*("[^"]*"|'[^']*'|[^\s>]+)/gi, '');
		}
	}

	function getPreviewFrame() {
		return qs('#wpps-el-preview-frame');
	}

	function freshPreviewFrame() {
		var old = getPreviewFrame();
		if (!old || !old.parentNode) {
			return null;
		}
		revokePreviewUrl();
		var next = document.createElement('iframe');
		next.id = 'wpps-el-preview-frame';
		next.className = old.className;
		next.title = old.getAttribute('title') || 'Email preview';
		next.setAttribute('sandbox', '');
		next.setAttribute('referrerpolicy', 'no-referrer');
		old.parentNode.replaceChild(next, old);
		return next;
	}

	function writePreviewHtml(frame, html) {
		if (!frame) {
			return;
		}
		var safe = sanitizePreviewHtml(html);
		revokePreviewUrl();
		frame.removeAttribute('srcdoc');
		try {
			previewObjectUrl = URL.createObjectURL(new Blob([safe], { type: 'text/html;charset=utf-8' }));
			frame.src = previewObjectUrl;
		} catch (e) {
			frame.src = 'about:blank';
			frame.srcdoc = safe;
		}
	}

	function showPreview(html) {
		var modal = qs('#wpps-el-preview-modal');
		if (!modal) {
			return;
		}
		openModal(modal);
		requestAnimationFrame(function () {
			requestAnimationFrame(function () {
				writePreviewHtml(freshPreviewFrame() || getPreviewFrame(), html);
			});
		});
	}

	function clearPreviewFrame() {
		revokePreviewUrl();
		var frame = getPreviewFrame();
		if (!frame) {
			return;
		}
		frame.src = 'about:blank';
		frame.srcdoc = PREVIEW_BLANK;
	}

	function metaItem(label, valueHtml) {
		return (
			'<div class="wpps-el-view-meta__item">' +
			'<span class="wpps-el-view-meta__label">' +
			escapeHtml(label) +
			'</span>' +
			'<span class="wpps-el-view-meta__value">' +
			valueHtml +
			'</span></div>'
		);
	}

	function headerRow(label, value) {
		if (!value) return '';
		return (
			'<div class="wpps-el-headers-grid__row">' +
			'<dt>' +
			escapeHtml(label) +
			'</dt><dd class="wpps-el-mono">' +
			escapeHtml(value) +
			'</dd></div>'
		);
	}

	function renderAttachmentsPanel(attachments) {
		var items = Array.isArray(attachments) ? attachments.filter(function (att) {
			return att && att.name;
		}) : [];

		var label = escapeHtml(i18n.attachments || 'Attachments');
		if (items.length) {
			label += ' (' + items.length + ')';
		}

		var html =
			'<details class="wpps-el-view-panel">' +
			'<summary class="wpps-el-view-panel__summary">' +
			'<span class="wpps-el-view-panel__label">' +
			label +
			'</span></summary>';

		if (!items.length) {
			html +=
				'<div class="wpps-el-view-empty"><p>' +
				escapeHtml(i18n.noAttachments || 'No attachments') +
				'</p></div></details>';
			return html;
		}

		html += '<ul class="wpps-el-attachments">';
		items.forEach(function (att) {
			var sizeLabel = att.size_label || '';
			html +=
				'<li class="wpps-el-attachments__item">' +
				'<span class="dashicons dashicons-media-default" aria-hidden="true"></span>' +
				'<span class="wpps-el-attachments__name wpps-el-mono">' +
				escapeHtml(att.name) +
				'</span>' +
				(sizeLabel
					? '<span class="wpps-el-attachments__size">' + escapeHtml(sizeLabel) + '</span>'
					: '') +
				'</li>';
		});
		html += '</ul></details>';
		return html;
	}

	function renderHeadersPanel(data, structured) {
		var rows = '';
		rows += headerRow(i18n.from || 'From', structured.from || data.from_email || '');
		rows += headerRow(i18n.replyTo || 'Reply-To', structured.reply_to || '');
		rows += headerRow(i18n.cc || 'Cc', structured.cc || '');
		rows += headerRow(i18n.bcc || 'Bcc', structured.bcc || '');
		rows += headerRow(i18n.contentType || 'Content-Type', structured.content_type || '');
		rows += headerRow(i18n.messageId || 'Message ID', structured.message_id || data.provider_message_id || '');

		var raw = data.headers || structured.raw || '';
		var html =
			'<details class="wpps-el-view-panel">' +
			'<summary class="wpps-el-view-panel__summary">' +
			'<span class="wpps-el-view-panel__label">' +
			escapeHtml(i18n.headers || 'Headers') +
			'</span></summary>';

		// Prefer structured fields; fall back to raw once (never both — duplicates From/etc.).
		if (rows) {
			html += '<dl class="wpps-el-headers-grid">' + rows + '</dl>';
		} else if (raw) {
			html += '<pre class="wpps-el-pre">' + escapeHtml(raw) + '</pre>';
		} else {
			html +=
				'<div class="wpps-el-view-empty"><p>' +
				escapeHtml(i18n.noHeaders || 'No headers were captured for this message.') +
				'</p></div>';
		}

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

	function renderDetailsPanel(data, structured) {
		var toEmail = data.to_email || '';
		var toHtml =
			toEmail && toEmail.indexOf(',') === -1 && toEmail.indexOf('@') !== -1
				? '<a href="mailto:' + escapeHtml(toEmail) + '">' + escapeHtml(toEmail) + '</a>'
				: escapeHtml(toEmail || '—');

		var fromDisplay = data.from_email || structured.from || '';
		var dateDisplay = data.sent_date_formatted || data.sent_date || '—';
		var provider = data.provider || '';
		var transport = data.transport || '';

		var hintParts = [];
		if (toEmail) {
			hintParts.push(toEmail);
		}
		if (fromDisplay) {
			hintParts.push(fromDisplay);
		}
		if (dateDisplay && dateDisplay !== '—') {
			hintParts.push(dateDisplay);
		}

		var meta = '';
		meta += metaItem(i18n.to || 'To', toHtml);
		meta += metaItem(
			i18n.from || 'From',
			fromDisplay
				? '<span class="wpps-el-mono">' + escapeHtml(fromDisplay) + '</span>'
				: escapeHtml('—')
		);
		meta += metaItem(i18n.date || 'Date', escapeHtml(dateDisplay));
		meta += metaItem(
			i18n.provider || 'Provider',
			'<span class="wpps-el-provider">' + escapeHtml(provider || '—') + '</span>'
		);
		if (transport && transport !== provider) {
			meta += metaItem(i18n.transport || 'Transport', escapeHtml(transport));
		}
		if (data.connection_id) {
			meta += metaItem(i18n.connection || 'Connection', escapeHtml(data.connection_id));
		}
		if (data.envelope_sender) {
			meta += metaItem(i18n.envelope || 'Envelope', escapeHtml(data.envelope_sender));
		}
		if (data.routing_reason) {
			meta += metaItem(i18n.routing || 'Routing', escapeHtml(data.routing_reason));
		}
		if (data.duration_ms > 0) {
			meta += metaItem(i18n.duration || 'Duration', escapeHtml(String(data.duration_ms) + ' ms'));
		}
		if (data.retry_count > 0) {
			meta += metaItem(i18n.retries || 'Retries', escapeHtml(String(data.retry_count)));
		}
		if (data.fallback_used) {
			meta += metaItem(i18n.fallback || 'Fallback', escapeHtml(i18n.yes || 'Yes'));
		}

		var html =
			'<details class="wpps-el-view-panel">' +
			'<summary class="wpps-el-view-panel__summary">' +
			'<span class="wpps-el-view-panel__label">' +
			escapeHtml(i18n.to || 'To') +
			'</span>' +
			(hintParts.length
				? '<span class="wpps-el-view-panel__hint">' + escapeHtml(hintParts.join(' · ')) + '</span>'
				: '') +
			'</summary>' +
			'<div class="wpps-el-view-meta">' +
			meta +
			'</div>';

		if (data.provider_message_id) {
			html +=
				'<div class="wpps-el-view-msgid">' +
				'<span class="wpps-el-view-meta__label">' +
				escapeHtml(i18n.messageId || 'Message ID') +
				'</span>' +
				'<div class="wpps-el-view-msgid__row">' +
				'<code id="wpps-el-msgid-value">' +
				escapeHtml(data.provider_message_id) +
				'</code>' +
				'<button type="button" class="button button-small" id="wpps-el-copy-msgid">' +
				escapeHtml(i18n.copy || 'Copy') +
				'</button></div></div>';
		}

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

	function renderView(data) {
		var body = qs('#wpps-el-view-body');
		var title = qs('#wpps-el-view-title');
		var badges = qs('#wpps-el-view-badges');
		var footer = qs('#wpps-el-view-footer');
		if (!body || !title) return;

		title.textContent = data.subject || i18n.noSubject || '(No subject)';

		var statusHtml = badge(data.status_label || data.status || '', 'wpps-el-badge--' + (data.status || 'pending'));
		if (data.delivery_status) {
			statusHtml += badge(data.delivery_label || data.delivery_status, 'wpps-el-delivery--' + data.delivery_status);
		}
		if (badges) {
			badges.innerHTML = statusHtml;
			badges.hidden = false;
		}

		var structured = data.headers_structured || {};

		var html = '<div class="wpps-el-view">';
		html += renderDetailsPanel(data, structured);

		if (data.error_message) {
			html +=
				'<div class="wpps-el-view-alert" role="alert">' +
				'<strong>' +
				escapeHtml(i18n.error || 'Error') +
				'</strong>' +
				'<p>' +
				escapeHtml(data.error_message) +
				'</p></div>';
		}

		html += renderHeadersPanel(data, structured);

		html +=
			'<details class="wpps-el-view-panel" open>' +
			'<summary class="wpps-el-view-panel__summary">' +
			'<span class="wpps-el-view-panel__label">' +
			escapeHtml(i18n.message || 'Message') +
			'</span>' +
			'</summary>';
		if (data.is_html && data.message) {
			html +=
				'<div class="wpps-el-preview-toolbar">' +
				'<button type="button" class="button button-small" id="wpps-el-preview-from-view">' +
				escapeHtml(i18n.previewHtml || 'Preview HTML') +
				'</button></div>';
		}
		if (data.content_logging_disabled) {
			html +=
				'<div class="wpps-el-view-empty">' +
				'<span class="dashicons dashicons-hidden" aria-hidden="true"></span>' +
				'<p>' +
				escapeHtml(i18n.contentDisabled || 'Message body was not stored. Enable “Store email body content in logs” in settings to keep bodies for future sends.') +
				'</p></div>';
		} else if (!data.message) {
			html +=
				'<div class="wpps-el-view-empty"><p>' +
				escapeHtml(i18n.noContent || '(No content)') +
				'</p></div>';
		} else {
			html += '<pre class="wpps-el-pre">' + escapeHtml(data.message) + '</pre>';
		}
		html += '</details>';

		html += renderAttachmentsPanel(data.attachments || []);
		html += '</div>';

		body.innerHTML = html;

		if (footer) {
			var actions =
				'<div class="wpps-el-modal-footer__start">' +
				'<a class="button" href="' +
				escapeHtml(data.delete_url) +
				'" onclick="return confirm(' +
				JSON.stringify(i18n.confirmDelete || 'Delete this log entry?') +
				');">' +
				escapeHtml(i18n.delete || 'Delete') +
				'</a></div><div class="wpps-el-modal-footer__end">';
			if (data.can_resend) {
				actions +=
					'<a class="button button-primary" href="' +
					escapeHtml(data.resend_url) +
					'">' +
					escapeHtml(i18n.resend || 'Resend') +
					'</a>';
			}
			actions += '</div>';
			footer.innerHTML = actions;
			footer.hidden = false;
		}

		var copyBtn = qs('#wpps-el-copy-msgid');
		if (copyBtn && data.provider_message_id && navigator.clipboard) {
			copyBtn.addEventListener('click', function () {
				navigator.clipboard.writeText(data.provider_message_id).then(function () {
					copyBtn.textContent = i18n.copied || 'Copied';
					setTimeout(function () {
						copyBtn.textContent = i18n.copy || 'Copy';
					}, 1500);
				});
			});
		}

		var previewBtn = qs('#wpps-el-preview-from-view');
		if (previewBtn) {
			var htmlSource = data.message || '';
			previewBtn.addEventListener('click', function (e) {
				e.preventDefault();
				e.stopPropagation();
				showPreview(htmlSource);
			});
		}
	}

	function loadLog(id) {
		var body = qs('#wpps-el-view-body');
		var modal = qs('#wpps-el-view-modal');
		var title = qs('#wpps-el-view-title');
		var badges = qs('#wpps-el-view-badges');
		var footer = qs('#wpps-el-view-footer');
		if (!body || !modal) return;

		if (title) {
			title.textContent = i18n.details || 'Email details';
		}
		if (badges) {
			badges.innerHTML = '';
			badges.hidden = true;
		}
		if (footer) {
			footer.innerHTML = '';
			footer.hidden = true;
		}
		body.innerHTML = '<p class="wpps-el-loading">' + escapeHtml(i18n.loading || 'Loading…') + '</p>';
		openModal(modal);

		var form = new FormData();
		form.append('action', 'wpps_email_logs_get');
		form.append('nonce', nonce);
		form.append('id', String(id));

		fetch(ajaxUrl, { method: 'POST', body: form, credentials: 'same-origin' })
			.then(function (r) {
				return r.json();
			})
			.then(function (res) {
				if (!res || !res.success || !res.data) {
					body.innerHTML =
						'<p class="wpps-el-error">' +
						escapeHtml((res && res.data && res.data.message) || i18n.loadError || 'Could not load log.') +
						'</p>';
					if (footer) {
						footer.hidden = true;
					}
					return;
				}
				renderView(res.data);
			})
			.catch(function () {
				body.innerHTML = '<p class="wpps-el-error">' + escapeHtml(i18n.loadError || 'Could not load log.') + '</p>';
				if (footer) {
					footer.hidden = true;
				}
			});
	}

	document.addEventListener('DOMContentLoaded', function () {
		var settingsModal = qs('#wpps-el-settings-modal');
		var viewModal = qs('#wpps-el-view-modal');
		var previewModal = qs('#wpps-el-preview-modal');

		var openSettings = qs('#wpps-el-open-settings');
		if (openSettings) {
			openSettings.addEventListener('click', function (e) {
				e.preventDefault();
				openModal(settingsModal);
			});
		}

		qsa('[data-wpps-el-close]').forEach(function (btn) {
			btn.addEventListener('click', function () {
				closeModal(btn.closest('.wpps-el-modal'));
				clearPreviewFrame();
			});
		});

		qsa('.wpps-el-modal').forEach(function (modal) {
			modal.addEventListener('click', function (e) {
				if (e.target === modal) {
					closeModal(modal);
					clearPreviewFrame();
				}
			});
		});

		document.addEventListener('keydown', function (e) {
			if (e.key === 'Escape') {
				closeAllModals();
				clearPreviewFrame();
			}
		});

		document.addEventListener('click', function (e) {
			var link = e.target.closest('.wpps-el-view-log');
			if (!link) return;
			e.preventDefault();
			var id = link.getAttribute('data-id');
			if (id) loadLog(id);
		});
	});
})();
