<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>
import Loading from '../Atoms/Loading.vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '../../utils/toast.ts'
import { toFeedUrl } from '../../utils/url.ts'

export default {
	name: 'Toplist',
	components: {
		Loading,
	},
	props: {
		type: {
			type: String,
			required: true,
		},
	},
	data: () => ({
		loading: true,
		tops: [],
	}),
	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(
				generateUrl(`/apps/repod/toplist/${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>
