<template>
	<div>
		<div>
			<h2>{{ t('repod', 'Hot podcasts') }}</h2>
			<Loading v-if="tops.hot.loading" />
			<ul v-if="!tops.hot.loading">
				<li v-for="top in tops.hot.items" :key="top.link">
					<TopItem :author="top.author"
						:image-url="top.imageUrl"
						:link="top.link"
						:title="top.title" />
				</li>
			</ul>
		</div>
		<div>
			<h2>{{ t('repod', 'New podcasts') }}</h2>
			<Loading v-if="tops.new.loading" />
			<ul v-if="!tops.new.loading">
				<li v-for="top in tops.new.items" :key="top.link">
					<TopItem :author="top.author"
						:image-url="top.imageUrl"
						:link="top.link"
						:title="top.title" />
				</li>
			</ul>
		</div>
	</div>
</template>

<script>
import Loading from '../Atoms/Loading.vue'
import TopItem from './TopItem.vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'

export default {
	name: 'TopList',
	components: {
		Loading,
		TopItem,
	},
	data() {
		return {
			tops: {
				hot: {
					items: [],
					loading: true,
				},
				new: {
					items: [],
					loading: true,
				},
			},
		}
	},
	async mounted() {
		this.loadList('hot')
		this.loadList('new')
	},
	methods: {
		async loadList(type) {
			try {
				this.tops[type].loading = true
				const toplist = await axios.get(generateUrl(`/apps/repod/toplist/${type}`))
				this.tops[type].items = toplist.data
			} catch (e) {
				console.error(e)
				showError(t('repod', 'Could not fetch tops'))
			} finally {
				this.tops[type].loading = false
			}
		},
	},
}
</script>

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

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

	ul {
		display: flex;
		gap: 2rem;
		overflow-x: auto;
		overflow-y: hidden;
		padding: .5rem;
	}
</style>
