<template>
	<div class="header">
		<img class="background" :src="feed.imageUrl" />
		<div class="content">
			<div>
				<NcAvatar
					:display-name="feed.author || feed.title"
					:is-no-user="true"
					:size="128"
					:url="feed.imageUrl" />
				<a class="feed" :href="url" @click.prevent="copyFeed">
					<RssIcon :size="20" />
					<i>{{ t('repod', 'Copy feed') }}</i>
				</a>
			</div>
			<div class="inner">
				<div class="infos">
					<h2>{{ feed.title }}</h2>
					<a :href="feed.link" target="_blank">
						<i>{{ feed.author }}</i>
					</a>
					<br /><br />
					<SafeHtml :source="feed.description || ''" />
				</div>
				<NcAppNavigationNew
					v-if="!getSubByUrl(url)"
					:text="t('repod', 'Subscribe')"
					@click="addSubscription">
					<template #icon>
						<PlusIcon :size="20" />
					</template>
				</NcAppNavigationNew>
			</div>
		</div>
	</div>
</template>

<script lang="ts">
import { NcAppNavigationNew, NcAvatar } from '@nextcloud/vue'
import { mapActions, mapState } from 'pinia'
import { showError, showSuccess } from '../../utils/toast.ts'
import PlusIcon from 'vue-material-design-icons/Plus.vue'
import type { PodcastDataInterface } from '../../utils/types.ts'
import RssIcon from 'vue-material-design-icons/Rss.vue'
import SafeHtml from '../Atoms/SafeHtml.vue'
import axios from '@nextcloud/axios'
import { decodeUrl } from '../../utils/url.ts'
import { generateUrl } from '@nextcloud/router'
import { t } from '@nextcloud/l10n'
import { useSubscriptions } from '../../store/subscriptions.ts'

export default {
	name: 'Banner',
	components: {
		NcAvatar,
		NcAppNavigationNew,
		PlusIcon,
		RssIcon,
		SafeHtml,
	},
	props: {
		feed: {
			type: Object as () => PodcastDataInterface,
			required: true,
		},
	},
	computed: {
		...mapState(useSubscriptions, ['getSubByUrl']),
		url() {
			return decodeUrl(this.$route.params.url as string)
		},
	},
	methods: {
		...mapActions(useSubscriptions, ['fetch']),
		t,
		async addSubscription() {
			try {
				await axios.post(
					generateUrl('/apps/gpoddersync/subscription_change/create'),
					{
						add: [this.url],
						remove: [],
					},
				)
			} catch (e) {
				console.error(e)
				showError(t('repod', 'Error while adding the feed'))
			}
			this.fetch()
		},
		copyFeed() {
			window.navigator.clipboard.writeText(this.url)
			showSuccess(t('repod', 'Link copied to the clipboard'))
		},
	},
}
</script>

<style scoped>
.background {
	filter: blur(1rem) brightness(50%);
	height: auto;
	left: 0;
	opacity: 0.4;
	position: absolute;
	top: 0;
	width: 100%;
	z-index: -1;
}

.content {
	display: flex;
	gap: 1rem;
	height: 10rem;
	position: relative;
}

.feed {
	display: flex;
	gap: 0.2rem;
	margin: 0.5rem;
}

.header {
	height: 14rem;
	overflow: hidden;
	padding: 2rem;
	position: relative;
}

.infos {
	flex: 1;
	overflow: auto;
}

.inner {
	display: flex;
	flex: 1;
}

@media only screen and (max-width: 768px) {
	.inner {
		flex-direction: column;
	}
}
</style>
