<template>
	<fragment>
		<p class="more">
			<span>{{ t('repod', 'Discover') }}</span>
			<NcButton v-if="showMore" @click="more">
				{{ t('repod', 'More') }}
			</NcButton>
		</p>
		<p>
			<NcLoadingIcon v-if="loading" />
			<ul v-if="!loading" class="tops">
				<li v-for="top in tops.feed.results" :key="top.id">
					<img :src="top.artworkUrl100" :alt="top.artistName" :title="top.artistName">
				</li>
			</ul>
			<span class="caption">{{ t('repod', 'Suggests by iTunes') }}</span>
		</p>
	</fragment>
</template>

<script>
import { NcButton, NcLoadingIcon } from '@nextcloud/vue'
import axios from '@nextcloud/axios'
import { generateUrl } from '@nextcloud/router'
import { showError } from '@nextcloud/dialogs'

export default {
	name: 'Top',
	components: {
		NcButton,
		NcLoadingIcon,
	},
	data() {
		return {
			tops: [],
			loading: true,
			showMore: true,
		}
	},
	computed: {
	},
	async mounted() {
		await this.fetch(10)
	},
	methods: {
		async more() {
			this.showMore = false
			await this.fetch(50)
		},
		async fetch(limit) {
			this.loading = true

			try {
				const top = await axios.get(generateUrl('/apps/repod/top/{limit}', { limit }))
				this.tops = top.data
			} catch (e) {
				console.error(e)
				showError(t('repod', 'Could not fetch tops'))
			}

			this.loading = false
		},
	},
}
</script>

<style scoped>
	.tops {
		display: flex;
		flex-wrap: wrap;
		gap: 2rem 5%;
		justify-content: center;
	}

	.tops li {
		flex-basis: 15%;
	}

	.tops li img {
		height: 100%;
		width: 100%;
	}

	.more {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.caption {
		float: right;
		font-size: small;
		margin: .5rem;
	}
</style>
