/**
 * Dennis GEO – Settings page admin JS
 * Handles AI populate modal, tabs, media upload, Google Maps coords, scroll-to-anchor
 */
(function() {
	var cfg = window.dseoSettings || {};

	/* Unsaved changes warning */
	var dirty = false;
	var form = document.querySelector('.dseo-settings form[action="options.php"]');
	if (form) {
		form.addEventListener('input', function() { dirty = true; });
		form.addEventListener('change', function() { dirty = true; });
		form.addEventListener('submit', function() { dirty = false; });
	}
	window.addEventListener('beforeunload', function(e) {
		if (dirty) { e.preventDefault(); e.returnValue = ''; }
	});

	/* Scroll to hash and highlight */
	var dseoScrollTarget = window.location.hash ? window.location.hash.replace('#', '') : '';
	function scrollToAndHighlight(id) {
		var el = document.getElementById(id);
		if (el) {
			el.scrollIntoView({ behavior: 'smooth', block: 'center' });
			el.style.boxShadow = '0 0 0 3px #d63638';
			setTimeout(function() { el.style.boxShadow = ''; }, 3000);
		}
	}

	/* "Clear fields" link inside the AI modal — close modal, scroll, highlight */
	var clearLink = document.getElementById('dseo-goto-clear');
	if (clearLink) {
		clearLink.addEventListener('click', function(e) {
			e.preventDefault();
			var modal = document.getElementById('dseo-ai-modal');
			if (modal) modal.classList.remove('active');
			setTimeout(function() { scrollToAndHighlight('dseo-clear-fields'); }, 200);
		});
	}

	/* Close modal on overlay click */
	document.querySelectorAll('.dseo-ai-modal-overlay').forEach(function(o) {
		o.addEventListener('click', function(e) { if (e.target === o) o.classList.remove('active'); });
	});

	var tabs = document.querySelectorAll('.dseo-settings-tab');
	var panels = document.querySelectorAll('.dseo-settings-panel');
	var hiddenTab = document.getElementById('dseo-active-tab');

	/* Restore active tab from URL hash or hidden field */
	var hash = window.location.hash.replace('#', '');
	var activeTab = (hash && document.querySelector('.dseo-settings-tab[data-stab="' + hash + '"]')) ? hash : (hiddenTab.value || 'identity');

	function switchTab(tabName) {
		tabs.forEach(function(t) { t.classList.remove('active'); });
		panels.forEach(function(p) { p.classList.remove('active'); });
		var tab = document.querySelector('[data-stab="' + tabName + '"]');
		var panel = document.querySelector('[data-spanel="' + tabName + '"]');
		if (tab && panel) {
			tab.classList.add('active');
			panel.classList.add('active');
			hiddenTab.value = tabName;
			window.location.hash = tabName;
		}
	}

	/* Init */
	switchTab(activeTab);

	/* Click handler */
	tabs.forEach(function(tab) {
		tab.addEventListener('click', function() {
			switchTab(tab.dataset.stab);
		});
	});

	/* Before form submit: store active tab in hidden field */
	var form = document.querySelector('.dseo-settings form');
	if (form) {
		form.addEventListener('submit', function() {
			hiddenTab.value = document.querySelector('.dseo-settings-tab.active').dataset.stab;
		});
	}

	/* Restore tab after settings save */
	var params = new URLSearchParams(window.location.search);
	if (params.get('settings-updated') === 'true' && activeTab) {
		switchTab(activeTab);
	}

	/* Media upload buttons */
	document.querySelectorAll('.dseo-upload-btn').forEach(function(btn) {
		btn.addEventListener('click', function(e) {
			e.preventDefault();
			var targetId = btn.dataset.target;
			var input = document.getElementById(targetId);
			var frame = wp.media({
				title: cfg.i18n.selectImage,
				button: { text: cfg.i18n.useImage },
				multiple: false,
				library: { type: 'image' }
			});
			frame.on('select', function() {
				var attachment = frame.state().get('selection').first().toJSON();
				input.value = attachment.url;
				var preview = input.closest('td').querySelector('img');
				if (preview) {
					preview.src = attachment.url;
				} else {
					var div = document.createElement('div');
					div.style.marginTop = '8px';
					div.innerHTML = '<img src="' + attachment.url + '" style="max-width:200px;max-height:80px;border:1px solid #ddd;border-radius:4px;padding:2px;" />';
					input.closest('td').appendChild(div);
				}
			});
			frame.open();
		});
	});

	/* AI Populate button */
	var populateBtn = document.getElementById('dseo-populate-btn');
	if (populateBtn) {
		populateBtn.addEventListener('click', function() {
			var btn = this;
			btn.disabled = true;
			btn.textContent = cfg.i18n.generatingKey;
			var xhr = new XMLHttpRequest();
			xhr.open('POST', cfg.ajaxUrl);
			xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			xhr.onload = function() {
				if (xhr.status === 200) {
					try {
						var resp = JSON.parse(xhr.responseText);
						if (resp.success) {
							var url = 'https://api.dennisgeo.com/checkout.php?site=' + encodeURIComponent(cfg.homeUrl) + '&key=' + encodeURIComponent(resp.data.key);
							window.open(url, '_blank');
							var modalBody = document.querySelector('#dseo-ai-modal .dseo-ai-modal-body');
							var modalFooter = document.querySelector('#dseo-ai-modal .dseo-ai-modal-footer');
							if (modalBody) {
								modalBody.innerHTML = '<div style="text-align:center;padding:20px 0;" id="dseo-populate-status-container">' +
									'<div style="font-size:48px;line-height:1;margin-bottom:16px;color:#7e5cef;">\u2713</div>' +
									'<h3 style="margin:0 0 12px;font-size:18px;">' + cfg.i18n.checkoutOpened + '</h3>' +
									'<p style="margin:0 0 10px;">' + cfg.i18n.dennisWorking + '</p>' +
									'<p style="margin:0 0 16px;">' + cfg.i18n.notifyWhenDone + '</p>' +
									'<div style="display:flex;justify-content:center;gap:4px;margin-bottom:8px;"><span style="width:8px;height:8px;background:#7e5cef;border-radius:50%;animation:dseo-bounce 1.4s infinite ease-in-out both;"></span><span style="width:8px;height:8px;background:#7e5cef;border-radius:50%;animation:dseo-bounce 1.4s infinite ease-in-out both;animation-delay:0.2s;"></span><span style="width:8px;height:8px;background:#7e5cef;border-radius:50%;animation:dseo-bounce 1.4s infinite ease-in-out both;animation-delay:0.4s;"></span></div>' +
									'</div>';
							}
							if (modalFooter) {
								modalFooter.innerHTML = '<button type="button" class="dseo-ai-modal-cta" onclick="document.getElementById(\'dseo-ai-modal\').classList.remove(\'active\');">' + cfg.i18n.close + '</button>';
							}
							dseoStartPolling();
							return;
						}
					} catch(e) {}
				}
				btn.textContent = cfg.i18n.errorTryAgain;
				btn.disabled = false;
			};
			xhr.send('action=dennis_seo_generate_api_key&nonce=' + cfg.nonce);
		});
	}

	var dseoPollInterval = null;
	function dseoStartPolling() {
		if (dseoPollInterval) return;
		dseoPollInterval = setInterval(function() {
			var x = new XMLHttpRequest();
			x.open('POST', cfg.ajaxUrl);
			x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
			x.onload = function() {
				try {
					var r = JSON.parse(x.responseText);
					if (r.success && r.data.status === 'completed') {
						clearInterval(dseoPollInterval);
						dseoPollInterval = null;
						var container = document.getElementById('dseo-populate-status-container');
						if (container) {
							container.innerHTML = '<div style="font-size:48px;line-height:1;margin-bottom:16px;color:#00a32a;">\ud83c\udf89</div>' +
								'<h3 style="margin:0 0 12px;font-size:18px;">' + cfg.i18n.populated + '</h3>' +
								'<p style="margin:0 0 16px;">' + cfg.i18n.reloadResults + '</p>' +
								'<button onclick="location.reload();" class="dseo-ai-modal-cta" style="background:linear-gradient(135deg,#00a32a,#007017);">' + cfg.i18n.reloadPage + '</button>';
						}
						var notice = document.createElement('div');
						notice.className = 'notice notice-success is-dismissible';
						notice.innerHTML = '<p><strong>' + cfg.i18n.dennisGeo + '</strong> ' + cfg.i18n.populatedNotice + ' <a href="#" onclick="location.reload();return false;">' + cfg.i18n.reloadNow + '</a></p>';
						var wrap = document.querySelector('.wrap, #wpbody-content');
						if (wrap) wrap.insertBefore(notice, wrap.firstChild);
					}
				} catch(e) {}
			};
			x.send('action=dennis_seo_check_status&nonce=' + cfg.statusNonce);
		}, 15000);
	}

	/* Google Maps coordinate extractor */
	window.dseoExtractCoords = function() {
		var url = document.getElementById('dseo-maps-url').value;
		var msg = document.getElementById('dseo-maps-msg');
		var match = url.match(/@(-?\d+\.?\d*),(-?\d+\.?\d*)/);
		if (match) {
			var latField = document.querySelector('input[name="dennis_seo_settings[org_geo_lat]"]');
			var lngField = document.querySelector('input[name="dennis_seo_settings[org_geo_lng]"]');
			if (latField) latField.value = match[1];
			if (lngField) lngField.value = match[2];
			msg.style.display = 'block';
			msg.style.color = '#00a32a';
			msg.textContent = cfg.i18n.coordsExtracted;
		} else {
			msg.style.display = 'block';
			msg.style.color = '#d63638';
			msg.textContent = cfg.i18n.coordsNotFound;
		}
	};

	/* Delayed scroll to anchor — runs after tabs have initialized */
	if (dseoScrollTarget && document.getElementById(dseoScrollTarget)) {
		setTimeout(function() { scrollToAndHighlight(dseoScrollTarget); }, 500);
	}
})();
