<template>
	<div>
		<h2>{{ title }}</h2>
		<Loading v-if="loading" />
		<ul v-if="!loading">
			<li v-for="top in items" :key="top.link">
				<router-link :to="toUrl(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 '@nextcloud/dialogs'
import { toUrl } from '../../utils/url.js'

export default {
	name: 'Tops',
	components: {
		Loading,
	},
	props: {
		type: {
			type: String,
			required: true,
		},
	},
	data() {
		return {
			items: [],
			loading: true,
		}
	},
	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() {
		this.loadList()
	},
	methods: {
		toUrl,
		async loadList() {
			try {
				this.loading = true
				const toplist = await axios.get(generateUrl(`/apps/repod/toplist/${this.type}`))
				this.items = toplist.data
			} catch (e) {
				console.error(e)
				showError(t('repod', 'Could not fetch tops'))
			} finally {
				this.loading = false
			}
		},
	},
}
</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: .5rem;
	}
</style>
