/**
 * GoValid QR — Verification page script.
 *
 * Data is passed via govalidVerifyData (wp_localize_script).
 *
 * @package GoValid_QR
 */
(function() {
	var config = window.govalidVerifyData || {};
	var token  = config.token  || '';
	var apiUrl = config.apiUrl || '';
	var i18n   = config.i18n  || {};

	var loadingEl = document.getElementById( 'govalid-verify-loading' );
	var resultEl  = document.getElementById( 'govalid-verify-result' );
	var errorEl   = document.getElementById( 'govalid-verify-error' );

	if ( ! token ) {
		showError( i18n.noToken, i18n.noTokenMsg );
		return;
	}

	var xhr = new XMLHttpRequest();
	xhr.open( 'GET', apiUrl, true );
	xhr.timeout = 15000;

	xhr.onload = function() {
		if ( xhr.status === 200 ) {
			try {
				var raw  = JSON.parse( xhr.responseText );
				var data = raw.content ? raw.content : raw;
				if ( data.success && data.verified ) {
					showResult( data );
				} else {
					showError( i18n.notVerified, data.message || i18n.notVerifiedMsg );
				}
			} catch ( e ) {
				showError( i18n.verifyError, i18n.verifyErrorMsg );
			}
		} else if ( xhr.status === 404 ) {
			showError( i18n.notFound, i18n.notFoundMsg );
		} else if ( xhr.status === 429 ) {
			showError( i18n.tooManyRequests, i18n.tooManyRequestsMsg );
		} else {
			showError( i18n.verifyFailed, i18n.verifyFailedMsg );
		}
	};

	xhr.onerror = function() {
		showError( i18n.connError, i18n.connErrorMsg );
	};

	xhr.ontimeout = function() {
		showError( i18n.timeout, i18n.timeoutMsg );
	};

	xhr.send();

	function showResult( data ) {
		loadingEl.style.display = 'none';
		resultEl.style.display  = 'block';

		var qr      = data.qr_code || {};
		var creator = data.creator || {};
		var ac      = data.anti_counterfeit || {};
		var hasViolations = ac.has_violations || false;

		var statusEl   = document.getElementById( 'govalid-verify-status' );
		var statusIcon = statusEl.querySelector( '.govalid-verify-status-icon' );
		var statusText = document.getElementById( 'govalid-verify-status-text' );
		var statusSub  = document.getElementById( 'govalid-verify-status-sub' );

		if ( hasViolations && ac.action === 'block' ) {
			statusEl.className = 'govalid-verify-status counterfeit';
			statusIcon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="15" y1="9" x2="9" y2="15"></line><line x1="9" y1="9" x2="15" y2="15"></line></svg>';
			statusText.textContent = i18n.counterfeit;
			statusSub.textContent  = i18n.counterfeitMsg;
		} else if ( hasViolations ) {
			statusEl.className = 'govalid-verify-status inactive';
			statusIcon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M10.29 3.86L1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z"></path><line x1="12" y1="9" x2="12" y2="13"></line><line x1="12" y1="17" x2="12.01" y2="17"></line></svg>';
			statusText.textContent = i18n.warnings;
			statusSub.textContent  = i18n.warningsMsg;
		} else if ( ! qr.is_active ) {
			statusEl.className = 'govalid-verify-status inactive';
			statusIcon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="8" x2="12" y2="12"></line><line x1="12" y1="16" x2="12.01" y2="16"></line></svg>';
			statusText.textContent = i18n.inactive;
			statusSub.textContent  = i18n.inactiveMsg;
		} else {
			statusEl.className = 'govalid-verify-status verified';
			statusIcon.innerHTML = '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"></path><polyline points="22 4 12 14.01 9 11.01"></polyline></svg>';
			statusText.textContent = i18n.verified;
			statusSub.textContent  = i18n.verifiedMsg;
		}

		setText( 'govalid-verify-name', qr.name || '-' );
		setText( 'govalid-verify-type', formatType( qr.qr_type, qr.template_type ) );
		setText( 'govalid-verify-scans', ( qr.scan_count || 0 ).toLocaleString() );

		var creatorName = creator.full_name || creator.username || '-';
		if ( creator.is_verified || creator.staff_verified ) creatorName += ' \u2713';
		setText( 'govalid-verify-creator', creatorName );

		if ( creator.institution_name ) {
			setText( 'govalid-verify-institution', creator.institution_name );
		} else {
			hideRow( 'govalid-row-institution' );
		}

		var activeEl = document.getElementById( 'govalid-verify-active' );
		if ( qr.is_active ) {
			activeEl.innerHTML = '<span class="govalid-verify-badge active">' + escapeHtml( i18n.active ) + '</span>';
		} else {
			activeEl.innerHTML = '<span class="govalid-verify-badge inactive">' + escapeHtml( i18n.inactiveBadge ) + '</span>';
		}

		if ( qr.created_at ) {
			setText( 'govalid-verify-created', new Date( qr.created_at ).toLocaleDateString( undefined, { year: 'numeric', month: 'long', day: 'numeric' } ) );
		} else {
			hideRow( 'govalid-row-created' );
		}

		if ( hasViolations && ac.violations && ac.violations.length > 0 ) {
			document.getElementById( 'govalid-verify-violations' ).style.display = 'block';
			var listEl = document.getElementById( 'govalid-violations-list' );
			var html = '';
			for ( var i = 0; i < ac.violations.length; i++ ) {
				var v = ac.violations[ i ];
				html += '<div class="govalid-verify-violation-item"><strong>' + escapeHtml( v.title || v.type ) + '</strong>';
				if ( v.message ) html += escapeHtml( v.message );
				html += '</div>';
			}
			listEl.innerHTML = html;
		}
	}

	function showError( title, message ) {
		loadingEl.style.display = 'none';
		errorEl.style.display   = 'block';
		document.getElementById( 'govalid-error-title' ).textContent   = title;
		document.getElementById( 'govalid-error-message' ).textContent = message;
	}

	function setText( id, text ) {
		var el = document.getElementById( id );
		if ( el ) el.textContent = text;
	}

	function hideRow( id ) {
		var el = document.getElementById( id );
		if ( el ) el.style.display = 'none';
	}

	function formatType( qrType, templateType ) {
		var types = { url: 'URL', vcard: 'vCard', wifi: 'WiFi', text: 'Text', email: 'Email', sms: 'SMS', phone: 'Phone', location: 'Location' };
		return types[ qrType ] || qrType || templateType || '-';
	}

	function escapeHtml( str ) {
		var d = document.createElement( 'div' );
		d.appendChild( document.createTextNode( str ) );
		return d.innerHTML;
	}
})();
