/**
 * Dennis GEO – Audit page admin JS
 */
(function() {
var cfg = window.dseoAudit || {};
		(function() {
var btn = document.getElementById('dseo-run-btn');
var intro = document.getElementById('dseo-audit-intro');
var loading = document.getElementById('dseo-audit-loading');
var results = document.getElementById('dseo-audit-results');
var fill = document.getElementById('dseo-loading-fill');
var pct = document.getElementById('dseo-loading-pct');
var auditData = null;
var animDone = false;

btn.addEventListener('click', function() {
	intro.style.display = 'none';
	loading.style.display = 'block';
	startAnimation();
	fetchAudit();
});

var dotTimer = null;

function animateDots(stepEl) {
	if (dotTimer) clearInterval(dotTimer);
	var dots = stepEl.querySelector('.dseo-dots');
	var count = 0;
	dots.textContent = '';
	dotTimer = setInterval(function() {
		count = (count % 3) + 1;
		dots.textContent = '.'.repeat(count);
	}, 400);
}

function stopDots(stepEl) {
	if (dotTimer) { clearInterval(dotTimer); dotTimer = null; }
	stepEl.querySelector('.dseo-dots').textContent = '...';
}

function startAnimation() {
	var steps = [
		{ el: 'dseo-step-1', pct: 15, time: 0 },
		{ el: 'dseo-step-2', pct: 40, time: 3000 },
		{ el: 'dseo-step-3', pct: 65, time: 6500 },
		{ el: 'dseo-step-4', pct: 80, time: 10000 },
		{ el: 'dseo-step-5', pct: 95, time: 12500 },
	];

	steps.forEach(function(step, i) {
		setTimeout(function() {
fill.style.width = step.pct + '%';
pct.textContent = step.pct + '%';
if (i > 0) {
	var prev = document.getElementById(steps[i-1].el);
	prev.classList.remove('active');
	prev.classList.add('done');
	stopDots(prev);
}
var el = document.getElementById(step.el);
el.classList.add('active');
animateDots(el);
		}, step.time);
	});

	setTimeout(function() {
		var last = document.getElementById('dseo-step-5');
		last.classList.remove('active');
		last.classList.add('done');
		stopDots(last);
		fill.style.width = '100%';
		pct.textContent = '100%';
		animDone = true;
		maybeShowResults();
	}, 15000);
}

function fetchAudit() {
	var xhr = new XMLHttpRequest();
	xhr.open('POST', cfg.ajaxUrl);
	xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
	xhr.timeout = 30000;
	xhr.onload = function() {
		if (xhr.status === 200) {
try {
	var resp = JSON.parse(xhr.responseText);
	if (resp.success) {
		auditData = resp.data;
		maybeShowResults();
		return;
	}
} catch(e) {}
		}
		showAuditError();
	};
	xhr.onerror = function() { showAuditError(); };
	xhr.ontimeout = function() { showAuditError(); };
	xhr.send('action=dennis_seo_run_audit&nonce=' + cfg.auditNonce + '');
}

function showAuditError() {
	loading.innerHTML = '<div style="padding:40px;text-align:center;">' +
		'<span class="dashicons dashicons-warning" style="font-size:48px;width:48px;height:48px;color:#d63638;margin-bottom:16px;"></span>' +
		'<h2 style="margin:0 0 8px;font-size:18px;">' + cfg.i18n.auditFailed + '</h2>' +
		'<p style="color:#555;">' + cfg.i18n.somethingWrong + '</p>' +
		'<button onclick="location.reload();" style="margin-top:12px;padding:10px 24px;background:#7e5cef;color:#fff;border:none;border-radius:6px;cursor:pointer;font-size:14px;">' + cfg.i18n.tryAgain + '</button>' +
		'</div>';
}

function maybeShowResults() {
	if (!auditData || !animDone) return;
	setTimeout(function() {
		loading.style.display = 'none';
		results.style.display = 'block';
		renderResults(auditData);
	}, 500);
}

function scoreColor(pct) {
	if (pct <= 30) return '#d63638';
	if (pct <= 60) return '#dba617';
	if (pct <= 85) return '#72a832';
	if (pct <= 94) return '#00a32a';
	return '#00a32a';
}

function scoreMsg(pct) {
	if (pct <= 30) return '' + cfg.i18n.scoreCritical + '';
	if (pct <= 60) return '' + cfg.i18n.scoreNeedsWork + '';
	if (pct <= 85) return '' + cfg.i18n.scoreGood + '';
	if (pct <= 94) return '' + cfg.i18n.scoreAlmost + '';
	return '' + cfg.i18n.scorePerfect + '';
}

function renderResults(d) {
	var color = scoreColor(d.total);
	var html = '';

	// Gauge
	html += '<div class="dseo-gauge">';
	html += '<div class="dseo-gauge-circle" style="border-color:' + color + ';">';
	html += '<div class="dseo-gauge-num" style="color:' + color + ';">' + d.total + '%</div>';
	html += '<div class="dseo-gauge-label">AI Visibility Score</div>';
	html += '</div>';
	html += '<div class="dseo-gauge-msg" style="color:' + color + ';">' + scoreMsg(d.total) + '</div>';
	html += '</div>';

	// Global Settings
	html += renderCategory('' + cfg.i18n.globalSettings + '', d.scores.global, d.global.checks);

	// Page SEO
	html += renderPageStats('' + cfg.i18n.pageSeo + ' (' + d.pages.total_pages + ' ' + cfg.i18n.pages + ')', d.scores.pages, d.pages.field_stats);

	// llms-full.txt
	html += renderCategory('llms-full.txt', d.scores.llms, d.llms.checks);

	// Recommendations — build context-aware tips from the audit data
	var recs = [];
	var globalChecks = d.global.checks;
	var failedGlobal = 0;
	var hasGeoLat = true;
	var hasPhone = true;
	var hasSocial = true;
	var hasLlms = true;
	var hasOgImage = true;
	for (var gi = 0; gi < globalChecks.length; gi++) {
		if (!globalChecks[gi].passed) {
failedGlobal++;
if (globalChecks[gi].label === 'Geo latitude' || globalChecks[gi].label === 'Geo longitude') hasGeoLat = false;
if (globalChecks[gi].label === 'Phone number') hasPhone = false;
if (globalChecks[gi].label === 'Social profile (at least 1)') hasSocial = false;
if (globalChecks[gi].label === 'llms.txt enabled') hasLlms = false;
if (globalChecks[gi].label === 'Default OG image') hasOgImage = false;
		}
	}

	// First-time / very low score — encouraging start
	if (d.total < 30) {
		recs.push('' + cfg.i18n.recGreatStart + '');
	} else if (d.scores.global < 100 && failedGlobal > 5) {
		recs.push('' + cfg.i18n.recPartialGlobal + '');
	} else if (d.scores.global < 100) {
		recs.push('' + cfg.i18n.recAlmostGlobal + '');
	}

	// Specific missing fields
	if (!hasGeoLat) {
		recs.push('' + cfg.i18n.recGeoMissing + '');
	}
	if (!hasPhone) {
		recs.push('' + cfg.i18n.recPhoneMissing + '');
	}
	if (!hasSocial) {
		recs.push('' + cfg.i18n.recSocialMissing + '');
	}
	if (!hasOgImage) {
		recs.push('' + cfg.i18n.recOgImageMissing + '');
	}
	if (!hasLlms) {
		recs.push('' + cfg.i18n.recLlmsDisabled + '');
	}

	// Page-level
	if (d.scores.pages < 100 && d.scores.pages > 0) {
		recs.push('' + cfg.i18n.recPagesMissing + '');
	} else if (d.scores.pages === 0 && d.pages.total_pages > 0) {
		recs.push('' + cfg.i18n.recPagesNone + '');
	}

	// llms-full.txt
	if (d.scores.llms < 100) {
		recs.push('' + cfg.i18n.recLlmsFullMissing + '');
	}

	// Good score tips
	if (d.total >= 80) {
		recs.push('' + cfg.i18n.recAddFaq + '');
		recs.push('' + cfg.i18n.recSubmitSitemap + '');
	}

	if (recs.length > 0) {
		html += '<div style="background:#f8f9fa;border:1px solid #e2e4e7;border-radius:8px;padding:20px;margin-bottom:20px;">';
		html += '<h3 style="margin:0 0 12px;font-size:15px;"><span class="dashicons dashicons-lightbulb" style="color:#dba617;margin-right:4px;"></span> ' + cfg.i18n.recommendations + '</h3>';
		html += '<ul style="margin:0;padding-left:18px;">';
		for (var ri = 0; ri < recs.length; ri++) {
html += '<li style="font-size:13px;line-height:1.7;color:#1d2327;margin-bottom:6px;">' + recs[ri] + '</li>';
		}
		html += '</ul>';
		html += '</div>';
	}

	// CTA
	if (d.total < 80) {
		html += '<div class="dseo-cta" style="padding:0;overflow:hidden;">';
		html += '<div style="background:linear-gradient(135deg,#7e5cef 0%,#5b3dc7 100%);padding:30px 24px;color:#fff;position:relative;border-radius:8px 8px 0 0;">';
		html += '<img src="' + cfg.dennisLogoUrl + '" alt="" style="position:absolute;top:16px;right:16px;width:75px;height:75px;opacity:0.7;">';
		html += '<h3 style="margin:0 0 6px;font-size:18px;font-weight:600;color:#fff;"><span class="dashicons dashicons-superhero-alt" style="color:#fff;margin-right:6px;"></span> ' + cfg.i18n.tooManyFields + '</h3>';
		html += '<p style="margin:0;font-size:14px;opacity:0.9;color:#fff;">' + cfg.i18n.fillOneClick + '</p>';
		html += '</div>';
		html += '<div style="padding:24px;">';
		html += '<p>' + cfg.i18n.aiDescription + '</p>';
		html += '<p style="font-size:12px;color:#666;margin-bottom:12px;">' + cfg.i18n.fieldsLeftAsIs + ' <a href="' + cfg.clearFieldsUrl + '" style="color:#7e5cef;">' + cfg.i18n.clearFields + '</a> ' + cfg.i18n.first + '</p>';
		html += '<p style="font-size:11px;color:#888;margin-bottom:12px;">' + cfg.i18n.serviceDisclaimer + '</p>';
		html += '<button class="dseo-cta-btn" id="dseo-audit-populate-btn" onclick="dseoPopulate(this);">';
		html += '<span class="dashicons dashicons-superhero-alt" style="margin-top:3px;"></span> ' + cfg.i18n.checkout + '';
		html += '</button>';
		html += '</div></div>';
	} else {
		html += '<div class="dseo-cta dseo-cta-success">';
		html += '<h3>' + cfg.i18n.techComplete + '</h3>';
		html += '<p>' + cfg.i18n.techCompleteDesc + '</p>';
		html += '<a href="https://dennisgeo.com/wordpress-ai-visibility-audit.html" target="_blank" class="dseo-cta-btn" style="background:linear-gradient(135deg,#00a32a,#007017);">';
		html += '' + cfg.i18n.learnMore + ' &rarr;';
		html += '</a>';
		html += '</div>';
	}

	// Run again
	html += '<div style="text-align:center;margin-top:16px;">';
	html += '<button onclick="location.reload();" style="background:none;border:1px solid #ccc;padding:8px 16px;border-radius:4px;cursor:pointer;font-size:13px;color:#555;">' + cfg.i18n.runAgain + '</button>';
	html += '</div>';

	results.innerHTML = html;
}

function renderCategory(title, scorePct, checks) {
	var color = scoreColor(scorePct);
	var html = '<div class="dseo-cat">';
	html += '<div class="dseo-cat-header"><span class="dseo-cat-title">' + title + '</span><span class="dseo-cat-score" style="color:' + color + ';">' + scorePct + '%</span></div>';
	html += '<div class="dseo-cat-bar"><div class="dseo-cat-bar-fill" style="width:' + scorePct + '%;background:' + color + ';"></div></div>';
	html += '<div class="dseo-checks">';
	checks.forEach(function(c) {
		var cls = c.passed ? 'dseo-check-pass' : 'dseo-check-fail';
		html += '<div class="dseo-check ' + cls + '">' + c.label + '</div>';
	});
	html += '</div></div>';
	return html;
}

function renderPageStats(title, scorePct, stats) {
	var color = scoreColor(scorePct);
	var html = '<div class="dseo-cat">';
	html += '<div class="dseo-cat-header"><span class="dseo-cat-title">' + title + '</span><span class="dseo-cat-score" style="color:' + color + ';">' + scorePct + '%</span></div>';
	html += '<div class="dseo-cat-bar"><div class="dseo-cat-bar-fill" style="width:' + scorePct + '%;background:' + color + ';"></div></div>';
	html += '<div class="dseo-page-stats">';
	stats.forEach(function(s) {
		var pct = s.total > 0 ? Math.round((s.filled / s.total) * 100) : 0;
		var c = scoreColor(pct);
		html += '<div class="dseo-page-stat">';
		html += '<span class="dseo-page-stat-label">' + s.label + '</span>';
		html += '<div class="dseo-page-stat-bar"><div class="dseo-page-stat-fill" style="width:' + pct + '%;background:' + c + ';"></div></div>';
		html += '<span class="dseo-page-stat-num" style="color:' + c + ';">' + s.filled + '/' + s.total + '</span>';
		html += '</div>';
	});
	html += '</div></div>';
	return html;
}
		})();

		window.dseoPopulate = function(btn) {
btn.disabled = true;
btn.innerHTML = '' + 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 cta = btn.closest('.dseo-cta');
	if (cta) {
		cta.id = 'dseo-populate-status-cta';
		cta.innerHTML = '<div style="text-align:center;padding:20px 0;">' +
'<div style="font-size:48px;line-height:1;margin-bottom:12px;color:#7e5cef;">✓</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>';
	}
	dseoStartPollingAudit();
	return;
}
		} catch(e) {}
	}
	btn.innerHTML = '' + cfg.i18n.errorTryAgain + '';
	btn.disabled = false;
};
xhr.send('action=dennis_seo_generate_api_key&nonce=' + cfg.populateNonce + '');
		}

		var dseoPollIntervalAudit = null;
		function dseoStartPollingAudit() {
if (dseoPollIntervalAudit) return;
dseoPollIntervalAudit = 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(dseoPollIntervalAudit);
	dseoPollIntervalAudit = null;
	var cta = document.getElementById('dseo-populate-status-cta');
	if (cta) {
		cta.innerHTML = '<div style="text-align:center;padding:20px 0;">' +
'<div style="font-size:48px;line-height:1;margin-bottom:12px;color:#00a32a;">🎉</div>' +
'<h3 style="margin:0 0 10px;color:#00a32a;">' + cfg.i18n.populated + '</h3>' +
'<p style="margin:0 0 16px;">' + cfg.i18n.reloadAudit + '</p>' +
'<button onclick="location.reload();" class="dseo-cta-btn" style="background:linear-gradient(135deg,#00a32a,#007017);">' + cfg.i18n.reloadPage + '</button>' +
'</div>';
	}
}
		} catch(e) {}
	};
	x.send('action=dennis_seo_check_status&nonce=' + cfg.statusNonce);
}, 15000);
		}

})();
