/**
 * Dennis GEO – Meta Box admin JS
 * Handles tabs, character counters, media upload, AI populate modal
 */
(function() {
	var cfg = window.dseoMetaBox || {};


	/* AI Populate button */
	var populateBtn = document.getElementById('dseo-populate-btn-mb');
	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-mb .dseo-ai-modal-body');
							var modalFooter = document.querySelector('#dseo-ai-modal-mb .dseo-ai-modal-footer');
							if (modalBody) {
								modalBody.innerHTML = '<div style="text-align:center;padding:20px 0;" id="dseo-populate-status-container-mb">' +
									'<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-mb\').classList.remove(\'active\');">' + cfg.i18n.close + '</button>';
							}
							dseoStartPollingMb();
							return;
						}
					} catch(e) {}
				}
				btn.textContent = cfg.i18n.errorTryAgain;
				btn.disabled = false;
			};
			xhr.send('action=dennis_seo_generate_api_key&nonce=' + cfg.nonce);
		});
	}

	var dseoPollIntervalMb = null;
	function dseoStartPollingMb() {
		if (dseoPollIntervalMb) return;
		dseoPollIntervalMb = 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(dseoPollIntervalMb);
						dseoPollIntervalMb = null;
						var container = document.getElementById('dseo-populate-status-container-mb');
						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>';
						}
					}
				} catch(e) {}
			};
			x.send('action=dennis_seo_check_status&nonce=' + cfg.statusNonce);
		}, 15000);
	}

	/* 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'); });
	});

	/* Tab switching */
	var tabs = document.querySelectorAll('.dseo-tab');
	var panels = document.querySelectorAll('.dseo-panel');
	tabs.forEach(function(tab) {
		tab.addEventListener('click', function() {
			tabs.forEach(function(t) { t.classList.remove('active'); });
			panels.forEach(function(p) { p.classList.remove('active'); });
			tab.classList.add('active');
			var target = document.querySelector('[data-panel="' + tab.dataset.tab + '"]');
			if (target) target.classList.add('active');
		});
	});

	/* Character counters with progress bar */
	document.querySelectorAll('[data-char-count]').forEach(function(field) {
		var counter = document.getElementById(field.dataset.charCount);
		var fill = document.getElementById(field.dataset.charCount.replace('-count', '-fill'));
		var max = parseInt(field.dataset.charMax, 10);
		function update() {
			var len = field.value.length;
			var pct = Math.min((len / max) * 100, 100);
			counter.textContent = len + ' / ' + max;
			counter.className = 'dseo-char-text' + (len > max ? ' over' : '');
			if (fill) {
				fill.style.width = Math.min(pct, 110) + '%';
				fill.className = 'dseo-char-fill ' + (len > max ? 'over' : len < max * 0.5 ? 'warn' : 'good');
			}
		}
		field.addEventListener('input', update);
		update();
	});

	/* Media upload buttons in meta box */
	document.querySelectorAll('.dseo-mb-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 = document.querySelector('.dseo-mb-preview[data-for="' + targetId + '"]');
				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;" class="dseo-mb-preview" data-for="' + targetId + '" />';
					btn.closest('.dseo-row').insertBefore(div, btn.closest('.dseo-row').querySelector('.dseo-hint'));
				}
			});
			frame.open();
		});
	});
})();
