{% extends "_root.html" %}
{% block body %}
<div class="h-app">
	<h2 class="p-name"><a href="" class="u-url">Sample IndieAuth app</a></h2>
	<img width="128px" height="128px"
			style="float: right"
			alt="A person in a canoe rowing to the right"
		src="https://raw.githubusercontent.com/apancik/public-domain-icons/master/dist/human%20canoe.svg"
		class="u-logo" />
	<p class="p-note">
		This is meant to be a simple IndieAuth app that
		developers can use to test out their IndieAuth implementations. You can exchange an
		authorization code for a profile or token.
	</p>
	<p>The icons used for this project are from <a
			href="https://github.com/apancik/public-domain-icons">https://github.com/apancik/public-domain-icons</a>.
	</p>
</div>

<form id="auth-form" action="client/auth">
	<fieldset role="group">
	<input type="url" id="me-input" required name="me" autocomplete="me home" placeholder="Your implementation's
	profile URL" value="{{ me|default("") }}" />
		<button type="button" id="check-support-btn">Examine</button>
		<button type="submit" id="continue-btn" disabled>Continue</button>
	</fieldset>
</form>

<div id="support-status" style="display: none;">
	<!-- Support status will be displayed here -->
</div>

<script>
async function checkSupport() {
	const meInput = document.getElementById('me-input');
	const checkBtn = document.getElementById('check-support-btn');
	const continueBtn = document.getElementById('continue-btn');
	const statusDiv = document.getElementById('support-status');
	
	const url = meInput.value.trim();
	if (!url) {
		alert('Please enter a URL');
		return;
	}
	
	// Check cache first
	const cacheKey = `indieauth-support-${url}`;
	const cached = sessionStorage.getItem(cacheKey);
	if (cached) {
		const result = JSON.parse(cached);
		displayResult(result);
		return;
	}
	
	// Show loading state
	checkBtn.disabled = true;
	checkBtn.textContent = 'Checking...';
	statusDiv.style.display = 'block';
	statusDiv.innerHTML = '<div>Checking IndieAuth support...</div>';
	
	try {
		const response = await fetch(`/client/check-support?me=${encodeURIComponent(url)}`);
		const result = await response.json();
		
		// Cache the result
		sessionStorage.setItem(cacheKey, JSON.stringify(result));
		
		displayResult(result);
	} catch (error) {
		statusDiv.innerHTML = `
			<article class="status-error">
				<header class="status-error-header">
					Error checking support
				</header>
				<div class="status-box-content">
					${error.message || 'Network error occurred'}
				</div>
			</article>
		`;
	} finally {
		checkBtn.disabled = false;
		checkBtn.textContent = 'Examine';
	}
}

function displayResult(result) {
	const continueBtn = document.getElementById('continue-btn');
	const statusDiv = document.getElementById('support-status');
	
	if (result.supported && result.metadata) {
		const meta = result.metadata;
		const scopeBadges = (meta.scopes_supported && Array.isArray(meta.scopes_supported) && meta.scopes_supported.length > 0)
			? meta.scopes_supported.map(scope => `<span class="scope-badge">${scope}</span>`).join(' ')
			: '<em>None specified</em>';
		
		statusDiv.innerHTML = `
			<article class="status-success">
				<header class="status-success-header">
					IndieAuth Supported
				</header>
				<div class="status-box-content">
					<div><strong>Issuer:</strong> ${meta.issuer || '<em>Not specified</em>'}</div>
					<div><strong>Authorization:</strong> ${meta.authorization_endpoint || '<em>Not specified</em>'}</div>
					<div><strong>Token:</strong> ${meta.token_endpoint || '<em>Not specified</em>'}</div>
					${meta.introspection_endpoint ? `<div><strong>Introspection:</strong> ${meta.introspection_endpoint}</div>` : ''}
					${meta.revocation_endpoint ? `<div><strong>Revocation:</strong> ${meta.revocation_endpoint}</div>` : ''}
					${meta.ticket_endpoint ? `<div><strong>Ticket:</strong> ${meta.ticket_endpoint}</div>` : ''}
					<div><strong>PKCE Methods:</strong> ${(meta.code_challenge_methods_supported && Array.isArray(meta.code_challenge_methods_supported)) ? meta.code_challenge_methods_supported.join(', ') : '<em>None specified</em>'}</div>
					<div><strong>Scopes:</strong> ${scopeBadges}</div>
					${result.discovery_method ? `<div class="status-muted">Discovered via: ${result.discovery_method}</div>` : ''}
				</div>
			</article>
		`;
		continueBtn.disabled = false;
	} else {
		statusDiv.innerHTML = `
			<article class="status-error">
				<header class="status-error-header">
					Not Supported
				</header>
				<div class="status-box-content">
					${result.error || 'This site does not support IndieAuth.'}
				</div>
			</article>
		`;
		continueBtn.disabled = true;
	}
	
	statusDiv.style.display = 'block';
	
	// Add demo credentials section if present
	if (result.demo_credentials && result.demo_credentials.length > 0) {
		const credsHtml = `
			<article class="status-info">
				<header class="status-info-header">
					Demo Credentials for Testing
				</header>
				<div class="status-box-content">
					${result.demo_credentials.map(cred => `
						<div class="demo-credential">
							<div class="credential-row">
								<strong>Username:</strong> <code>${cred.username}</code>
								<button class="copy-btn" data-value="${cred.username}">Copy</button>
							</div>
							<div class="credential-row">
								<strong>Password:</strong> <code>${cred.password}</code>
								<button class="copy-btn" data-value="${cred.password}">Copy</button>
							</div>
							<div class="credential-row">
								<strong>Profile:</strong> <span>${cred.profile.me}</span>
							</div>
							<div class="credential-row">
								<strong>Name:</strong> <span>${cred.profile.name}</span>
							</div>
							${cred.profile.email ? `<div class="credential-row"><strong>Email:</strong> <span>${cred.profile.email}</span></div>` : ''}
							${cred.profile.photo ? `<div class="credential-row"><strong>Photo:</strong> <span>${cred.profile.photo}</span></div>` : ''}
						</div>
					`).join('<hr>')}
				</div>
			</article>
		`;
		statusDiv.innerHTML += credsHtml;
		
		// Set up copy button handlers
		statusDiv.querySelectorAll('.copy-btn').forEach(btn => {
			btn.addEventListener('click', function() {
				const value = this.dataset.value;
				navigator.clipboard.writeText(value).then(() => {
					const originalText = this.textContent;
					this.textContent = 'Copied!';
					setTimeout(() => this.textContent = originalText, 1500);
				});
			});
		});
	}
}

// Set up event listeners
document.getElementById('check-support-btn').addEventListener('click', checkSupport);
document.getElementById('me-input').addEventListener('keypress', function(e) {
	if (e.key === 'Enter') {
		e.preventDefault();
		checkSupport();
	}
});

// Clear cache when form is submitted
document.getElementById('auth-form').addEventListener('submit', function() {
	sessionStorage.clear();
});
</script>
{% endblock %}
