<script lang="ts">
	import { onMount } from 'svelte';
	import { fetchUptimeChecks, fetchInitialUptimeChecks } from './lib/atproto.ts';
	import UptimeDisplay from './lib/uptime-display.svelte';
	import type { UptimeCheckRecord } from './lib/types.ts';
	import { config } from './lib/config.ts';

	let checks = $state<UptimeCheckRecord[]>([]);
	let loading = $state(false);
	let error = $state('');
	let lastUpdate = $state<Date | null>(null);
	let hasRecentEvents = $state(true);
	let initialLoadComplete = $state(false);
	let isLoadingMore = $state(false);

	/**
	 * checks if there are any events in the configured threshold period
	 */
	function checkForRecentEvents(records: UptimeCheckRecord[]): boolean {
		const thresholdMinutes = config.inactivityThresholdMinutes || 5;
		const thresholdTimeAgo = new Date(Date.now() - thresholdMinutes * 60 * 1000);
		return records.some(record => record.indexedAt > thresholdTimeAgo);
	}

	async function loadChecks() {
		if (!initialLoadComplete) {
			isLoadingMore = true;
		} else {
			loading = true;
		}
		error = '';

		try {
			if (!initialLoadComplete) {
				// Initial load: fetch records progressively and show in real-time
				await fetchInitialUptimeChecks(config.pds, config.did, (progressRecords) => {
					checks = progressRecords;
					lastUpdate = new Date();
					hasRecentEvents = checkForRecentEvents(progressRecords);
				});
				initialLoadComplete = true;
			} else {
				// Refresh: fetch only new records and append them
				const result = await fetchUptimeChecks(config.pds, config.did);
				if (result.records.length > 0) {
					// Check if we actually have new records by comparing with existing ones
					const existingUris = new Set(checks.map(c => c.uri));
					const newRecords = result.records.filter(r => !existingUris.has(r.uri));
					
					if (newRecords.length > 0) {
						checks = newRecords.concat(checks); // prepend new records
					}
				}
				lastUpdate = new Date();
				hasRecentEvents = checkForRecentEvents(checks);
			}
		} catch (err) {
			error = (err as Error).message || 'failed to fetch uptime checks';
			checks = [];
		} finally {
			loading = false;
			isLoadingMore = false;
		}
	}

	onMount(() => {
		// load checks immediately
		loadChecks();

		// refresh every 10 seconds
		const interval = setInterval(loadChecks, 10 * 1000);
		return () => clearInterval(interval);
	});
</script>

<main class="max-w-6xl mx-auto p-8">
	<header class="text-center mb-8">
		<h1 class="text-5xl font-bold text-accent mb-2">{config.title}</h1>
		<p class="text-muted-foreground">{config.subtitle}</p>
	</header>

	<div class="bg-card rounded-lg shadow-sm p-4 mb-8 flex justify-between items-center">
		<div class="flex items-center gap-4">
			{#if lastUpdate}
				<span class="text-sm text-muted-foreground">
					last updated: {lastUpdate.toLocaleTimeString()}
				</span>
			{/if}
			{#if isLoadingMore}
				<span class="text-sm text-primary animate-pulse">
					fetching more data...
				</span>
			{/if}
		</div>
		<button 
			class="px-4 py-2 bg-primary text-primary-foreground rounded-md text-sm font-medium hover:opacity-90 disabled:opacity-50 transition-opacity" 
			onclick={loadChecks} 
			disabled={loading || isLoadingMore}
		>
			{loading || isLoadingMore ? 'loading...' : 'refresh'}
		</button>
	</div>

	{#if error}
		<div class="bg-destructive/10 text-destructive rounded-lg p-4 mb-4">
			{error}
		</div>
	{/if}

	{#if config.showInactivityWarning && !hasRecentEvents && checks.length > 0}
		<div class="bg-yellow-50 border border-yellow-200 text-yellow-800 rounded-lg p-4 mb-4">
			<strong>⚠️ Warning:</strong> No uptime pings received in the last {config.inactivityThresholdMinutes || 5} minutes. 
			The uptime monitor may be offline or experiencing issues.
		</div>
	{/if}

	{#if loading && checks.length === 0}
		<div class="text-center py-12 bg-card rounded-lg shadow-sm text-muted-foreground">
			fetching uptime data...
		</div>
	{:else}
		<UptimeDisplay {checks} />
	{/if}

	<footer class="mt-12 pt-8 border-t border-border text-center text-sm text-muted-foreground">
		<p>
			built by <a href="https://bsky.app/profile/nekomimi.pet" target="_blank" rel="noopener noreferrer" class="text-accent hover:underline">@nekomimi.pet</a>
			· <a href="https://tangled.org/@nekomimi.pet/cute-monitor" target="_blank" rel="noopener noreferrer" class="text-accent hover:underline">source</a>
		</p>
	</footer>
</main>

