<template>
	<NcGuestContent class="guest">
		<Loading v-if="!currentFavoriteData" />
		<NcAvatar
			v-if="currentFavoriteData"
			class="avatar"
			:display-name="currentFavoriteData.author || currentFavoriteData.title"
			:is-no-user="true"
			:size="222"
			:url="currentFavoriteData.imageUrl" />
		<div class="list">
			<h2 class="title">{{ currentFavoriteData.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="url" />
			</ul>
		</div>
	</NcGuestContent>
</template>

<script>
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.js'
import { mapState } from 'pinia'
import { showError } from '../../utils/toast.js'
import { useSubscriptions } from '../../store/subscriptions.js'

export default {
	name: 'Favorites',
	components: {
		Episode,
		Loading,
		NcAvatar,
		NcGuestContent,
	},
	props: {
		url: {
			type: String,
			required: true,
		},
	},
	data: () => ({
		episodes: [],
		loading: true,
	}),
	computed: {
		...mapState(useSubscriptions, ['getFavorites']),
		currentFavoriteData() {
			return this.getFavorites.find((fav) => fav.url === this.url)
		},
	},
	async mounted() {
		try {
			this.loading = true
			const episodes = await axios.get(
				generateUrl('/apps/repod/episodes/list?url={url}', {
					url: this.url,
				}),
			)
			this.episodes = [...episodes.data]
				.sort(
					(a, b) => new Date(b.pubDate?.date) - new Date(a.pubDate?.date),
				)
				.filter((episode) => !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;
}

.list {
	flex: 1;
}

.title {
	text-align: center;
}

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