<template>
	<NcGuestContent class="guest">
		<Loading v-if="!feed.data" />
		<NcAvatar
			v-if="feed.data"
			class="avatar"
			:display-name="feed.data.author || feed.data.title"
			:is-no-user="true"
			:size="222"
			:title="feed.data.author"
			:url="feed.data.imageUrl" />
		<div v-if="feed.data" class="list">
			<h2 class="title">{{ feed.data.title }}</h2>
			<Loading v-if="loading" />
			<ul v-if="!loading">
				<Episode
					v-for="episode in episodes"
					:key="episode.guid"
					:episode="episode"
					:one-line="true"
					:url="feed.metrics.url" />
			</ul>
		</div>
	</NcGuestContent>
</template>

<script lang="ts">
import type { EpisodeInterface, SubscriptionInterface } from '../../utils/types.ts'
import { NcAvatar, NcGuestContent } from '@nextcloud/vue'
import Episode from './Episode.vue'
import Loading from '../Atoms/Loading.vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { hasEnded } from '../../utils/status.ts'
import { showError } from '../../utils/toast.ts'
import { t } from '@nextcloud/l10n'

export default {
	name: 'Favorite',
	components: {
		Episode,
		Loading,
		NcAvatar,
		NcGuestContent,
	},
	props: {
		feed: {
			type: Object as () => SubscriptionInterface,
			required: true,
		},
	},
	data: () => ({
		episodes: [] as EpisodeInterface[],
		loading: true,
	}),
	async mounted() {
		try {
			this.loading = true
			const episodes = await axios.get<EpisodeInterface[]>(
				generateUrl('/apps/repod/episodes/list?url={url}', {
					url: this.feed.metrics.url,
				}),
			)
			this.episodes = [...episodes.data]
				.sort(
					(a: EpisodeInterface, b: EpisodeInterface) =>
						new Date(b.pubDate?.date || '').getTime() -
						new Date(a.pubDate?.date || '').getTime(),
				)
				.filter((episode: EpisodeInterface) => !this.hasEnded(episode))
				.slice(0, 4)
		} catch (e) {
			console.error(e)
			showError(t('repod', 'Could not fetch episodes'))
		} finally {
			this.loading = false
		}
	},
	methods: {
		hasEnded,
	},
}
</script>

<style scoped>
.guest {
	display: flex;
	flex-wrap: wrap;
	gap: 1rem;
	margin: 20px !important;
}

.list {
	flex: 1;
}

.title {
	text-align: center;
}

@media only screen and (max-width: 768px) {
	.avatar {
		display: none;
	}
}
</style>
