<template>
	<div>
		<h2>{{ title }}</h2>
		<Loading v-if="loading" />
		<ul v-if="!loading">
			<li v-for="top in tops" :key="top.link">
				<router-link :to="toFeedUrl(top.link)">
					<img :src="top.imageUrl" :title="top.author" />
				</router-link>
			</li>
		</ul>
	</div>
</template>

<script lang="ts">
import Loading from '../Atoms/Loading.vue'
import type { PodcastDataInterface } from '../../utils/types.ts'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '../../utils/toast.ts'
import { t } from '@nextcloud/l10n'
import { toFeedUrl } from '../../utils/url.ts'

export default {
	name: 'Toplist',
	components: {
		Loading,
	},
	props: {
		type: {
			type: String,
			required: true,
		},
	},
	data: () => ({
		loading: true,
		tops: [] as PodcastDataInterface[],
	}),
	computed: {
		title() {
			switch (this.type) {
				case 'new':
					return t('repod', 'New podcasts')
				case 'hot':
					return t('repod', 'Hot podcasts')
				default:
					return this.type
			}
		},
	},
	async mounted() {
		try {
			this.loading = true
			const tops = await axios.get<PodcastDataInterface[]>(
				generateUrl('/apps/repod/toplist/{type}', { type: this.type }),
			)
			this.tops = tops.data
		} catch (e) {
			console.error(e)
			showError(t('repod', 'Could not fetch tops'))
		} finally {
			this.loading = false
		}
	},
	methods: {
		toFeedUrl,
	},
}
</script>

<style scoped>
h2 {
	margin: 1rem 0;
}

img {
	height: 100%;
	width: 100%;
}

li {
	flex-basis: 10rem;
	flex-shrink: 0;
}

ul {
	display: flex;
	gap: 2rem;
	overflow: scroll hidden;
	padding-bottom: 0.5rem;
}
</style>
