<script>
	import { onMount } from 'svelte';
	import Spinner from './Spinner.svelte';
	import Commit from './Commit.svelte';

	export let url;

	let feed = null;
	let error = null;

	async function fetchFeed() {
		try {
			const response = await fetch(url);
			if (!response.ok) {
				throw new Error(`HTTP error! status: ${response.status}`);
			}
			const text = await response.text();
			const parser = new DOMParser();
			const xml = parser.parseFromString(text, 'application/xml');
			const items = Array.from(xml.querySelectorAll('item')).map((item) => ({
				title: item.querySelector('title')?.textContent,
				link: item.querySelector('link')?.textContent,
				description: item.querySelector('description')?.textContent,
				published: item.querySelector('pubDate')?.textContent,
				author: item.querySelector('author')?.textContent,
				guid: item.querySelector('guid')?.textContent
			}));
			feed = items;
		} catch (err) {
			error = err.message;
		}
	}

	onMount(() => {
		fetchFeed();
	});
</script>

<div class="my-4">
	{#if error}
		<p>Error: {error}</p>
	{:else if !feed}
		<Spinner />
	{:else}
		<div class="flex flex-col gap-2">
			{#each feed.slice(0, 5) as commit}
				<Commit {...commit} />
			{/each}
		</div>
	{/if}
</div>
