/**
 * NewsSync Tools Page JavaScript
 *
 * @package NewsSync
 */

(function() {
	'use strict';

	const resultEl = document.getElementById('newssync-ajax-result');

	// This script can work even if resultEl doesn't exist (for toggle functionality).
	if (! resultEl && ! document.getElementById('newssync-toggle-docs')) {
		return;
	}

	/**
	 * Show admin notice.
	 *
	 * @param {string} type - Notice type (success, error, info).
	 * @param {string} message - Message to display.
	 */
	function showNotice(type, message) {
		if (! resultEl) {
			// debug removed: no DOM target to show notice
			return;
		}
		resultEl.innerHTML = '<div class="notice notice-' + escapeHtml(type) + '"><p>' + escapeHtml(message) + '</p></div>';

		// Auto-hide after 5 seconds with fade-out animation
		setTimeout(function() {
			const notice = resultEl.querySelector('.notice');
			if (notice) {
				notice.style.transition = 'opacity 0.4s ease';
				notice.style.opacity = '0';
				setTimeout(function() {
					resultEl.innerHTML = '';
				}, 400);
			}
		}, 5000);
	}

	/**
	 * Escape HTML to prevent XSS.
	 *
	 * @param {string} str - String to escape.
	 * @return {string} Escaped string.
	 */
	function escapeHtml(str) {
		if (! str) {
			return '';
		}
		return String(str)
			.replace(/&/g, '&amp;')
			.replace(/</g, '&lt;')
			.replace(/>/g, '&gt;')
			.replace(/"/g, '&quot;')
			.replace(/'/g, '&#039;');
	}

	/**
	 * Make AJAX request.
	 *
	 * @param {string} action - AJAX action.
	 * @param {Function} successCallback - Success callback.
	 * @param {string} loadingMsg - Loading message.
	 */
	function makeAjaxRequest(action, successCallback, loadingMsg) {
		if (resultEl) {
			resultEl.innerHTML = '<div class="notice notice-info"><p>' + escapeHtml(loadingMsg) + '</p></div>';
		}

		fetch(newssyncTools.ajaxUrl, {
			method: 'POST',
			credentials: 'same-origin',
			headers: {
				'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
			},
			body: new URLSearchParams({
				action:  action,
				_wpnonce: newssyncTools.nonce
			})
		})
		.then(function(response) {
			return response.json();
		})
		.then(function(json) {
			if (json.success) {
				successCallback(json);
			} else {
				const message = json.data && json.data.message ? json. data.message : newssyncTools.i18n. requestFailed;
				const detail = json.data && json.data.detail ? json.data.detail : '';

				if (detail) {
					if (resultEl) {
						resultEl.innerHTML = '<div class="notice notice-error"><p>' + escapeHtml(message) + '</p><pre style="white-space:  pre-wrap; background:#fff; padding:10px; border:  1px solid #ccc;">' + escapeHtml(detail) + '</pre></div>';
					} else {
						// debug removed: fallback to showing combined message
						alert(message + (detail ? '\n\n' + detail : ''));
					}
				} else {
					showNotice('error', message);
				}
			}
		})
		.catch(function() {
			showNotice('error', newssyncTools.i18n.requestFailed);
		});
	}

	// AJAX create table
	const createBtn = document.getElementById('newssync-ajax-create');
	if (createBtn) {
		createBtn.addEventListener('click', function(e) {
			e.preventDefault();
			makeAjaxRequest(
				'newssync_try_create_table',
				function(json) {
					showNotice('success', json.data.message);
					setTimeout(function() {
						location.reload();
					}, 1500);
				},
				newssyncTools.i18n.creatingTable
			);
		});
	}

	// Clear cache
	const clearCacheBtn = document.getElementById('newssync-clear-cache');
	if (clearCacheBtn) {
		clearCacheBtn. addEventListener('click', function(e) {
			e.preventDefault();

			if (! confirm(newssyncTools.i18n.confirmClear)) {
				return;
			}

			makeAjaxRequest(
				'newssync_clear_cache',
				function(json) {
					showNotice('success', json.data.message);
				},
				newssyncTools. i18n.clearingCache
			);
		});
	}

	// Clear error
	const clearErrorBtn = document. getElementById('newssync-clear-error');
	if (clearErrorBtn) {
		clearErrorBtn.addEventListener('click', function(e) {
			e.preventDefault();

			makeAjaxRequest(
				'newssync_clear_error',
				function(json) {
					showNotice('success', json.data.message);
					setTimeout(function() {
						location.reload();
					}, 1000);
				},
				'.. .'
			);
		});
	}

	// Toggle docs
	const toggleBtn = document.getElementById('newssync-toggle-docs');
	if (toggleBtn) {
		toggleBtn.addEventListener('click', function(e) {
			e.preventDefault();
			const panel = document.getElementById('newssync-docs-panel');
			if (! panel) {
				return;
			}
			panel.style.display = (panel.style.display === 'none' ? 'block' :  'none');
		});
	}

	// Dismiss notice
	const dismissBtn = document.getElementById('newssync-dismiss-notice');
	if (dismissBtn) {
		dismissBtn.addEventListener('click', function(e) {
			e.preventDefault();

			const nonce = dismissBtn.getAttribute('data-nonce');
			if (!nonce) {
				showNotice('error', 'Nonce missing');
				return;
			}

			if (resultEl) {
				resultEl.innerHTML = '<div class="notice notice-info"><p>Dismissing notice...</p></div>';
			}

			fetch(newssyncTools.ajaxUrl, {
				method: 'POST',
				credentials: 'same-origin',
				headers: {
					'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
				},
				body: new URLSearchParams({
					action: 'newssync_dismiss_table_notice',
					_wpnonce: nonce
				})
			})
			.then(function(response) {
				return response.json();
			})
			.then(function(json) {
				if (json.success) {
					showNotice('success', json.data && json.data.message ? json.data.message : 'Notice dismissed successfully');
				} else {
					const message = json.data && json.data.message ? json.data.message : 'Failed to dismiss notice';
					showNotice('error', message);
				}
			})
			.catch(function() {
				showNotice('error', 'Request failed');
			});
		});
	}

})();