/**
 * WTE Business Card — reCAPTCHA v3 Contact Page Integration
 */
'use strict';
document.addEventListener('DOMContentLoaded', function() {
	const btn = document.querySelector('.wte-contact__email-btn');
	if (!btn || typeof grecaptcha === 'undefined' || typeof wteRecaptcha === 'undefined') return;

	function rot13(str) {
		return str.replace(/[a-zA-Z]/g, function(c) {
			return String.fromCharCode((c <= 'Z' ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
		});
	}
	function wteRevealEmail() {
		const user = rot13(btn.dataset.user || '');
		const domain = rot13(btn.dataset.domain || '');
		if (user && domain) { window.location.href = 'mailto:' + user + '@' + domain; }
	}
	function wteShowSpamWarning() {
		alert('アクセスが拒否されました。しばらく経ってからお試しください。');
	}

	btn.addEventListener('click', function(e) {
		e.preventDefault();
		grecaptcha.ready(function() {
			grecaptcha.execute(wteRecaptcha.siteKey, { action: 'contact_view' })
				.then(function(token) {
					return fetch(wteRecaptcha.ajaxUrl, {
						method: 'POST',
						headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
						body: 'action=wte_verify_recaptcha&token=' + token + '&nonce=' + wteRecaptcha.nonce
					});
				})
				.then(function(r) { return r.json(); })
				.then(function(data) {
					if (data.success) { wteRevealEmail(); }
					else { wteShowSpamWarning(); }
				})
				.catch(function() { wteRevealEmail(); });
		});
	});
});
